Java Generics and numbers

后端 未结 11 968
离开以前
离开以前 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:35

    In Java the type is erased at runtime, so you need to pass in another argument to get the type at runtime.

    That could either be the value to initialise the arrays with, or the class to use.

    If you choose to pass in the class, then have a Map of class to value to store a zero value for each type.

    You then can use java.util.Arrays.fill to fill the array:

    private static HashMap, Object> ZEROS = new HashMap,Object>();
    
    static {
        ZEROS.put( Integer.class, Integer.valueOf(0) );
        ...
    }
    
    private static  T[][] zeroMatrix ( Class type, int rows, int cols ) {
        @SuppressWarnings("unchecked")
        T[][]   matrix  = (T[][]) java.lang.reflect.Array.newInstance(type, rows, cols);
        Object  zero    = ZEROS.get(type);
    
        for ( T[] row : matrix ) 
            java.util.Arrays.fill(row,zero);
    
        return matrix;
    }
    
    Integer[][] matrix = zeroMatrix (Integer.class, 10, 10);
    

    However, if performance is remotely a concern you don't want to be using boxed values for numeric code.

    You really don't want to try and use null for zero - it will treble the complexity of all other paths in your code. Although you might get away with a numeric support class which would provide addition and multiplication of the various boxed number types, the amount of complexity you save will be very little compared with providing two or three primitive matrices and a couple of big-number ones, particularly if you use a templating system (eg ant's replace task or XSLT) to generate the source code.

提交回复
热议问题