Java doesn't allow arrays of inner classes for a generic class

前端 未结 3 1528
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 12:04

I know that you cannot create an array of a generic type, Instead you have to resort to a hack. (Given Java supports generic arrays, just not their creation, it is not clear to

相关标签:
3条回答
  • 2021-02-07 12:09

    Do the following:

    @SuppressWarnings("unchecked")
    final Inner[] inners = (Inner[])new Outer<?>.Inner[16];
    

    The equivalent to your first example would have been new Outer.Inner[16] but this will isolate the unchecked cast and avoid the raw type.

    0 讨论(0)
  • 2021-02-07 12:15

    What you need to realize is that your situation is the same as the first situation you described.

    Inner is a non-static inner class of Outer, a generic class. That means Inner is within the scope of the type parameter, and simply writing Inner is short for Outer<E>.Inner. i.e. it may not look it, but simply Inner is a parameterized type, just like Map.Entry<K, V>, because the type parameter E of the outer class becomes implicitly a type parameter of the inner class. The solution to both problems is the same.

    Your solution to the first problem was to create an array of the raw type, i.e. new Map.Entry[numEntries];. What is the raw type here? Not Inner, as we already discussed. Instead, you need to explicitly qualify the outer type to access the raw type: new Outer.Inner[16];. Of course, you need a cast to cast it back into the desired generic array type:

    (Inner[])new Outer.Inner[16]
    

    There is another way to create an array of a generic type, without using a raw type -- using a wildcarded type, i.e. new Map.Entry<?, ?>[numEntries];. The equivalent for our case would be new Outer<?>.Inner[16];. With the cast:

    (Inner[])new Outer<?>.Inner[16]
    
    0 讨论(0)
  • Is it an option for you to make the inner class static?

    If that is possible you shold be able to create array of the inner class using the standard way:

    public class Outer<E> {
        final Inner[] inners = new Inner[16]; // works
    
        static class Inner {
        }
    }
    
    0 讨论(0)
提交回复
热议问题