Generic Arrays in Java
Arrays and generics create a programming roadblock in Java. You can't create an array of parametric types directly. This is because arrays are covariant, meaning they retain the type of their elements at runtime, while generics use type erasure.
A workaround is to use Array.newInstance() like this:
private Comparable[] hashtable; ... hashtable = (Comparable[])Array.newInstance(Comparable.class, tableSize);
However, it's important to note that this solution is not ideal.
Why not use generic arrays?
To avoid these issues, it's recommended to use an ArrayList instead of an array when working with generics. ArrayLists are covariant and type-safe, which makes them a better choice for storing generic types.
For a more detailed explanation, refer to the Java Generics FAQ:
Can I create an array whose component type is a concrete parameterized type?
No, because it is not type-safe.
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[].
The above is the detailed content of Why Can\'t I Create Generic Arrays in Java?. For more information, please follow other related articles on the PHP Chinese website!