Generic array creation error

You can’t have arrays of generic classes. Java simply doesn’t 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); 

Leave a Comment