java – Generic array creation error

java – Generic array creation error

You cant have arrays of generic classes. Java simply doesnt support it.

You should consider using a collection instead of an array. For instance,

public static ArrayList<List<MyObject>> a = new ArrayList<List<MyObject>();

Another workaround is to create an auxilliary class like this

class MyObjectArrayList extends ArrayList<MyObject> { }

and then create an array of MyObjectArrayList.

Here is a good article on why this is not allowed in the language. The article gives the following example of what could happen if it was allowed:

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); 

There is a easier way to create generic arrays than using List.

First, let

public static ArrayList<myObject>[] a = new ArrayList[2];

Then initialize

for(int i = 0; i < a.length; i++) {
     a[i] = new ArrayList<myObject>();

java – Generic array creation error

You can do

public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList<?>[2];


public static ArrayList<myObject>[] a = (ArrayList<myObject>[])new ArrayList[2];

(The former is probably better.) Both will cause unchecked warnings, which you can pretty much ignore or suppress by using: @SuppressWarnings(unchecked)

Leave a Reply

Your email address will not be published. Required fields are marked *