Java Generics and numbers

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

    You need to consider that generics are only used at compile-time for type safety checking. This information is lost at runtime so you can't use auto-boxing on retVal[i][j] = 0; since Java can't auto-box to type Number or Object.

    If you pass in the value you want to set, it will work. Here's a quick sample:

    private  T[][] fillMatrix(int row, int col, T value) {
        T[][] retVal = (T[][])new Object[row][col];
        for(int i = 0; i < row; i++) {
           for(int j = 0; j < col; j++) {
              retVal[i][j] = value;
           }
        }
        return retVal;
    }
    

    Btw, for(int i = row; i < row; i++) and for(int j = col; j < col; j++) will never loop so there's another problem with your code.

    edit: You won't be able to cast the result to something other than Object[][] though because that's the actual array type.

提交回复
热议问题