Creating Arrays of Generic Classes
When attempting to initialize an array of a generic class, such as ArrayList
Error Cause
Java does not support the direct creation of arrays of generic classes due to type safety concerns. If this functionality were allowed, it could lead to potential type errors, as illustrated in the following example:
<code class="java">List<String>[] lsa = new List<String>[10]; // illegal Object[] oa = lsa; // OK because List<String> is a subtype of Object List<Integer> li = new ArrayList<Integer>(); li.add(new Integer(3)); oa[0] = li; String s = lsa[0].get(0);</code>
In this scenario, the oa array is assigned to the lsa array, but then an Integer value is added to the list at index 0. When retrieving the element at index 0 from lsa and attempting to cast it to String, a ClassCastException would occur.
Workaround
To circumvent this limitation, consider using a collection instead of an array. For instance:
<code class="java">public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>>();</code>
Alternatively, an auxiliary class can be created to act as the array element type:
<code class="java">class MyObjectArrayList extends ArrayList<MyObject> { }</code>
<code class="java">MyObjectArrayList[] a = new MyObjectArrayList[2];</code>
By using a collection or auxiliary class, the Java compiler can ensure type safety and prevent potential errors.
The above is the detailed content of Why Can\'t I Create Arrays of Generic Classes in Java?. For more information, please follow other related articles on the PHP Chinese website!