简体   繁体   English

类型无法创建List的通用数组<FooClass>

[英]Type Cannot create a generic array of List<FooClass>

Suppose I have class FooClass. 假设我有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. 非常感谢任何帮助。

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: UPD:

If you want to create array of lists, you should: 如果要创建列表数组,则应该:

  1. Create array 创建数组
  2. Fill this array in with List instances 使用List实例填充此数组

Example: 例:

List<FooClass>[] runs = new List[4];
for (int i = 0; i < runs.length; i++) {
    runs[i] = new ArrayList<>();
}

It's not good idea to mix Generics and Array. 将Generics和Array混合起来并不是一个好主意。 Generics doesn't retain type information at run time so creating an array of generics fails. 泛型在运行时不保留类型信息,因此创建一系列泛型失败。

List should not be declared as array. List不应该声明为数组。 It should be: 它应该是:

List<FooClass> runs=new ArrayList<FooClass>(4);

or 要么

List<FooClass> runs=new ArrayList<FooClass>();

Edit : you can try List<ConfigParser> runs[] = new List[4]; 编辑 :您可以尝试List<ConfigParser> runs[] = new List[4]; . But why do you need array of Lists? 但为什么你需要一系列的列表?

Also as @rai.skumar has mentioned, Generic information is not retained during run time because of Type Erasure. 同样如@ rai.skumar所提到的,由于类型擦除,在运行时不保留通用信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM