Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 me why a hack is better than Java supporting creating generic arrays)

Instead of writing this

Map.Entry<K, V>[] entries = new Map.Entry<K, V>[numEntries];

you have to write this

@SuppressWarnings("unchecked")
Map.Entry<K, V>[] entries = (Map.Entry<K, V>) new Map.Entry[numEntries];

Unfortunately this doesn't work if you have an array of nested type of a generic

public class Outer<E> {
    final Inner[] inners = new Inner[16]; // Generic array creation

    class Inner {
    }
}

The best work around appears to be

@SuppressWarnings("unchecked")
final Inner[] inners = (Inner[]) Array.newInstance(Inner.class, 16);

Is this the most "elegant" solution?


I make seen Generic Array Creation Compilation Error From Inner Class but the solution here is worse IMHO.

like image 650
Peter Lawrey Avatar asked Dec 09 '13 16:12

Peter Lawrey


People also ask

Can you use generics with an array?

To understand the reason, you first need to know two arrays are covariant and generics are invariant. Because of this fundamental reason, arrays and generics do not fit well with each other.

What are the main disadvantages of using Java inner classes?

Inner classes have their disadvantages. From a maintenance point of view, inexperienced Java developers may find the inner class difficult to understand. The use of inner classes will also increase the total number of classes in your code.

Does Java support inner classes?

Inner Classes (Non-static Nested Classes)Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.

Can a class have multiple inner classes?

You can have more than one inner class in a class. As we defined earlier, it's easy to implement multiple inner classes.


1 Answers

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.

like image 70
Paul Bellora Avatar answered Oct 13 '22 15:10

Paul Bellora