In an attempt to see if I can clean up some of my math code, mostly matrix stuff, I am trying to use some Java Generics. I have the following method:
private <
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;
}
usage:
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));
EDIT
a generic matrix:
public static 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