java基础:19.2 泛型举例,矩阵的运算
首先创建一个泛型类,<E extends Number>
表示该泛型类型是Number的子类型。
接下来,申明3个抽象
方法,因为不知道元素的确切类型前不能实现它。
后面写的所有方法都是非静态的,因为我们使用的是泛型类型E来表示类。
public abstract class GenericMatrix <E extends Number>{ //矩阵元素的类型是Number 的泛型子类
protected abstract E add(E o1, E o2);
protected abstract E multiply(E o1, E o2);
protected abstract E zero(); //零矩阵
//矩阵的加法运算、乘法运算、结果显示
public E[][] addMatrix(E[][] matrix1, E[][] matrix2) { //将两个矩阵相加,用泛型E来表示类,所以方法是非静态的;
if ( (matrix1.length != matrix2.length) || (matrix1[0].length != matrix2[0].length) )
throw new RuntimeException("The matrices do not have the same size!");
E[][] result = (E[][]) new Number[matrix1.length][matrix1[0].length]; //注意E[][] result = new Number[matrix.length][matrix1[0].length]是不对的,
//因为不能用泛型类型来创建数组,要用(E[][])来转换才能创建数组;
for(int i = 0 ;i < result.length; i++)
for (int j = 0; j <result[i].length; j++) {
result [i][j] = add(matrix1[i][j],matrix2[i][j]);
}
return result;
}
//multiply
public E[][] multiplyMatrix(E[][] matrix1, E[][] matrix2) {
if (matrix1[0].length != matrix2.length)
throw new RuntimeException("The matrices do not have compatible size!");
E[][] result = (E[][]) new Number[matrix1.length][matrix2[0].length];
for(int i = 0 ;i < result.length; i++) {
for (int j = 0; j <result[0].length; j++) {
result [i][j] = zero();
for(int k= 0 ;k < matrix1[0].length; k++) {
result[i][j] = add(result[i][j],multiply(matrix1[i][k],matrix2[k][j]));
}
}
}
return result;
}
public static void printResult(Number[][] m1 ,Number[][] m2, Number[][] m3, char op) {
for(int i = 0; i<m1.length ; i++) {
for ( int j = 0; j < m1[0].length; j++)
System.out.print(" " + m1[i][j]);
if (i == m1.length / 2)
System.out.print(" " + op + " ");
else
System.out.print(" ");
for(int j = 0; j < m2.length; j++)
System.out.print(" " + m2[i][j]);
if (i == m1.length / 2)
System.out.print(" = ");
else
System.out.print(" ");
for(int j = 0; j < m3.length; j++)
System.out.print(m3[i][j] + " ");
System.out.println();
}
}
}
接下来是对GenericMatrix的Integer示例的部分函数重载
该程序实现了Integer 对象的add 、multiply 和zero 方法。因为这些方法只能被addMatrix 和multiplyMatrix 方法调用,所以,它们仍然是protected 的。
public class IntegerMatrix extends GenericMatrix<Integer>{
@Override
protected Integer add(Integer o1,Integer o2) {
return o1 + o2;
}
@Override
protected Integer multiply(Integer o1,Integer o2) {
return o1 * o2;
}
@Override
protected Integer zero() {
return 0;
}
}
main函数
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[][] m1 = new Integer[][] {{1,2,3},{4,5,6},{1,1,1}};
Integer[][] m2 = new Integer[][] {{1,1,1},{2,2,2},{0,0,0}};
IntegerMatrix integerMatrix = new IntegerMatrix();
System.out.println("\n m1 + m2 is ");
GenericMatrix.printResult(m1, m2, integerMatrix.addMatrix(m1, m2), '+');
System.out.println("\n m1 * m2 is ");
GenericMatrix.printResult(m1, m2, integerMatrix.multiplyMatrix(m1, m2), '*');
}
}
显示结果