Java Generics and numbers

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

    it should be null instead of zero.

    If you want to actually put in there the equivalent 0 for object T you will need to provide a factory of T. Something like this:

    interface Factory {
       T getZero();     
    }
    

    and you should make the method like this:

    private  T[][] zeroMatrix(int row, int col, Factory factory) {
        T[][] retVal = (T[][])new Object[row][col];
        for(int i = row; i < row; i++) {
            for(int j = col; j < col; j++) {
                retVal[i][j] = factory.getZero();
            }
        }
    
        return retVal;
    }
    

    You should also have proper implementations for the factory:

     class IntegerFactory implements Factory {
        Integer getZero() {
           return new Integer(0);
        }
    }
    

    Normally you would put the getMatrix(int row, int column) in the factory implementation too in order to actually return a proper typed array.

提交回复
热议问题