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.