Java Generics and numbers

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

    If you really want to use generics, you could do something like this

    private  T[][] zeroMatrix(int row, int col, Class clazz) throws InstantiationException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException
    {
        T[][] retVal = (T[][]) Array.newInstance(clazz, new int[] { row, col });
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                Constructor c = clazz.getDeclaredConstructors()[0];
                retVal[i][j] = c.newInstance("0");
            }
        }
    
        return retVal;
    }
    

    Example:

    zeroMatrix(12, 12, Integer.class);
    

提交回复
热议问题