<T extends Number> T[][] zeroMatrix(Class<? extends Number> of, int row, int col) {
T[][] matrix = (T[][]) java.lang.reflect.Array.newInstance(of, row, col);
T zero = (T) of.getConstructor(String.class).newInstance("0");
// not handling exception
for (int i = 0; i < row; i++) {
for (int j = 0; j < col;
matrix[i][j] = zero;
}
}
return matrix;
}
用法:
BigInteger[][] bigIntegerMatrix = zeroMatrix(BigInteger.class, 3, 3);
Integer[][] integerMatrix = zeroMatrix(Integer.class, 3, 3);
Float[][] floatMatrix = zeroMatrix(Float.class, 3, 3);
String[][] error = zeroMatrix(String.class, 3, 3); // <--- compile time error
System.out.println(Arrays.deepToString(bigIntegerMatrix));
System.out.println(Arrays.deepToString(integerMatrix));
System.out.println(Arrays.deepToString(floatMatrix));
编辑
一个通用矩阵:
public static <T> T[][] fillMatrix(Object fill, int row, int col) {
T[][] matrix = (T[][]) Array.newInstance(fill.getClass(), row, col);
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
matrix[i][j] = (T) fill;
}
}
return matrix;
}
Integer[][] zeroMatrix = fillMatrix(0, 3, 3); // a zero-filled 3x3 matrix
String[][] stringMatrix = fillMatrix("B", 2, 2); // a B-filled 2x2 matrix