Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Cannot create a generic array of List<FooClass>

Suppose I have class FooClass.

public class FooClass {
}

The following line gives me the following compile error:

// Note I want to create an array of length 4 of Lists of FooClass
List<FooClass> runs[]=new List<FooClass>[4];
Cannot create a generic array of List<FooClass> ...

Would appreciate any help.

like image 941
user1172468 Avatar asked Apr 03 '13 06:04

user1172468


2 Answers

List collection is not the same as array:

// if you want create a List of FooClass (you can use any List implementation)
List<FooClass> runs = new ArrayList<FooClass>();

// if you want create array of FooClass
FooClass[] runs = new FooClass[4];

UPD:

If you want to create array of lists, you should:

  1. Create array
  2. Fill this array in with List instances

Example:

List<FooClass>[] runs = new List[4];
for (int i = 0; i < runs.length; i++) {
    runs[i] = new ArrayList<>();
}
like image 88
bsiamionau Avatar answered Sep 26 '22 14:09

bsiamionau


It's not good idea to mix Generics and Array. Generics doesn't retain type information at run time so creating an array of generics fails.

like image 35
rai.skumar Avatar answered Sep 25 '22 14:09

rai.skumar