Generic Arrays in Java
In Java, generics and arrays do not directly coexist. When attempting to create an array of generics that extends a comparable type, an error may arise. The fundamental reason for this is that Java generics are erased during compilation.
Consider the following code:
<code class="java">public class Hash<T extends Comparable<String>> { private T[] hashTable; private int tableSize; Hash(int records, double load) { tableSize = (int)(records / loadFactor); tableSize = findNextPrime(tableSize); hashTable = (T[])(new Object[tableSize]); // Error: Object cannot be cast to Comparable } }</code>
Java's type erasure treats arrays as covariant, meaning they maintain the type of their elements at runtime. Therefore, an array of a generic type is not the same type as an array of its comparable type, and the latter cannot be cast to the former.
To circumvent this issue, one workaround is to use Array.newInstance():
<code class="java">private Comparable[] hashtable; ... hashtable = (Comparable[])Array.newInstance(Comparable.class, tableSize);</code>
However, this approach has limitations. Legacy code, external libraries, or interoperability with other languages may require true generic arrays.
Ultimately, it is generally recommended to avoid using arrays with generics in Java. Instead, consider utilizing collection classes like ArrayList or HashMap, which provide more flexibility and type safety.
The above is the detailed content of Why Can\'t I Create an Array of Generics in Java?. For more information, please follow other related articles on the PHP Chinese website!