我想创建一个如下所示的数组列表:
ArrayList<Individual>[] group = new ArrayList<Individual>()[4];
但它不是编译。我该怎么做呢?
我想创建一个如下所示的数组列表:
ArrayList<Individual>[] group = new ArrayList<Individual>()[4];
但它不是编译。我该怎么做呢?
当前回答
ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
al[i] = new ArrayList<String>();
}
其他回答
我想我有点晚了,但我遇到了同样的问题,必须按照我的项目的要求创建一个数组列表数组,以便将不同子类的对象存储在同一个地方,这是我最终所做的:
ArrayList<?>[] items = new ArrayList[4];
ArrayList<Chocolate> choc = new ArrayList<>();
ArrayList<Chips> chips = new ArrayList<>();
ArrayList<Water> water = new ArrayList<>();
ArrayList<SoftDrink> sd = new ArrayList<>();
因为数组中的每个数组列表都包含不同的对象(巧克力,薯条,水和软饮料) 这是一个模拟自动售货机的项目。 然后我将每个数组列表赋值给数组的一个下标:
items[0]=choc;
items[1]=chips;
items[2]=water;
items[3]=sd;
希望这对遇到类似问题的人有所帮助。
可以创建一个扩展ArrayList的类
class IndividualList extends ArrayList<Individual> {
}
然后创建数组
IndividualList[] group = new IndividualList[10];
根据Oracle文档:
不能创建参数化类型的数组
相反,你可以这样做:
ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);
正如Tom Hawting - tackline所建议的那样,更好的做法是:
List<List<Individual>> group = new ArrayList<List<Individual>>(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。
不能创建泛型类型的数组。创建数组列表:
List<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>();
或者如果你真的需要数组(警告:糟糕的设计!):
ArrayList[] group = new ArrayList[4];