Java Generics and numbers

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

    Ye olde (reference) arrays do not play well with generics. In this case arrays are also likely to be inefficient. You are creating an array of arrays, so there is unnecessary indirection and bounds checking. Better to make a class Matrix<T>. You may also want to add to the Matrix an reference to an instance of T that represents a zero.

    0 讨论(0)
  • 2021-02-05 09:41

    I think you are fighting a losing battle. Even if you solve this, how are you planning on solving addition, subtraction etc? The number class is not a very useful superclass, and about the only useful method is doubleValue().

    Zero can be defined as the identity in addition or a zero in multiplication, but without a generic definition of addition or multiplication, a generic definition of zero is unlikely.

    If you want this then you might be better just sticking with BigDecimal for everything, but of course that will have associated performance penalties.

    The other obvious option would be to leave the array with null initialisation, and then change your other code to treat null as zero.

    0 讨论(0)
  • 2021-02-05 09:41

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

    private <T extends Number> T[][] zeroMatrix(int row, int col, Class<T> 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<T> c = clazz.getDeclaredConstructors()[0];
                retVal[i][j] = c.newInstance("0");
            }
        }
    
        return retVal;
    }
    

    Example:

    zeroMatrix(12, 12, Integer.class);
    
    0 讨论(0)
  • 2021-02-05 09:43

    Arrays and Generics do not play well together:

    "Arrays are covariant, which means that an array of supertype references is a supertype of an array of subtype references. That is, Object[] is a supertype of String[] and a string array can be accessed through a reference variable of type Object[] ."

    see the Java Generics FAQ:

    • Can I create an array whose component type is a concrete parameterized type?
    • How do I generically create objects and arrays?
    0 讨论(0)
  • 2021-02-05 09:50

    I raised a related question which also asked about performance issues which referenced your question. The consensus was clear that refactoring to Generics had a considerable performance hit and so you should stick with primitives if this matters (for me it does).

    0 讨论(0)
提交回复
热议问题