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.
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.
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.
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.
You can have more than one inner class in a class. As we defined earlier, it's easy to implement multiple inner classes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With