我想创建一个如下所示的数组列表:

ArrayList<Individual>[] group = new ArrayList<Individual>()[4];

但它不是编译。我该怎么做呢?


当前回答

List[] listArr = new ArrayList[4];

上面这行给出了警告,但它是有效的(即它创建了ArrayList的数组)

其他回答

创建和初始化 对象[]yourArray = new对象[ARRAY_LENGTH]; 写访问 yourArray[我]= someArrayList; 访问内部数组列表的元素: ((ArrayList < YourType >) yourArray[我])阀门(elementOfYourType);//或其他方法 读访问 将数组元素i读取为数组列表使用类型转换: someElement= (ArrayList<YourType>) yourArray[i]; 对于数组元素i:读取数组列表元素在索引j处的值 arrayListElement= (ArrayList<YourType>) yourArray[i]).get(j);

你可以这样做 ArrayList<Individual>[] group = (ArrayList<Individual>[])new ArrayList[4];

您必须创建非泛型类型的数组,然后将其转换为泛型类型。

这是可行的,数组列表的数组。试着去理解它是如何工作的。

import java.util.*;

public class ArrayOfArrayList {
    public static void main(String[] args) {

        // Put the length of the array you need
        ArrayList<String>[] group = new ArrayList[15];
        for (int x = 0; x < group.length; x++) {
            group[x] = new ArrayList<>();
        }

        //Add some thing to first array
        group[0].add("Some");
        group[0].add("Code");

        //Add some thing to Secondarray
        group[1].add("In here");

        //Try to output 'em
        System.out.println(group[0]);
        System.out.println(group[1]);
    }
}

一些代码归功于Kelvincer。

ArrayList<Integer>[] graph = new ArrayList[numCourses] 它的工作原理。

正如其他人提到的,使用另一个List来存储数组列表可能更好,但如果你必须使用数组:

ArrayList<Individual>[] group = (ArrayList<Individual>[]) new ArrayList[4];

您需要取消警告,但在这种情况下是安全的。