Java Generics and numbers

后端 未结 11 965
离开以前
离开以前 2021-02-05 08:58

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 <         


        
11条回答
  •  孤街浪徒
    2021-02-05 09:33

     T[][] zeroMatrix(Class 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
    

提交回复
热议问题