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

use*_*468 6 java collections list

假设我有FooClass类.

public class FooClass {
}
Run Code Online (Sandbox Code Playgroud)

以下行给出了以下编译错误:

// Note I want to create an array of length 4 of Lists of FooClass
List<FooClass> runs[]=new List<FooClass>[4];
Run Code Online (Sandbox Code Playgroud)
Cannot create a generic array of List<FooClass> ...
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助.

bsi*_*nau 6

列表集合与数组不同:

// 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];
Run Code Online (Sandbox Code Playgroud)

UPD:

如果要创建列表数组,则应该:

  1. 创建数组
  2. 使用List实例填充此数组

例:

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

  • 我不是选民,但我认为OP要求创建列表而不是单个列表. (2认同)