Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic array creation error

I am trying do something like this:-

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

myObject is a class. I am getting this error:- Generic array creation (arrow is pointing to new.)

like image 304
Harshveer Singh Avatar asked Aug 20 '11 12:08

Harshveer Singh


People also ask

Why can't you create a generic array Java?

The reason this is impossible is that Java implements its Generics purely on the compiler level, and there is only one class file generated for each class. This is called Type Erasure. At runtime, the compiled class needs to handle all of its uses with the same bytecode.

Can you create an array of generic type?

No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.

Can generic arrays be created in Java?

Java allows generic classes, methods, etc. that can be declared independent of types. However, Java does not allow the array to be generic. The reason for this is that in Java, arrays contain information related to their components and this information is used to allocate memory at runtime.


2 Answers

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);  
like image 188
aioobe Avatar answered Oct 02 '22 13:10

aioobe


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>(); } 
like image 37
Strin Avatar answered Oct 02 '22 13:10

Strin