我想创建一个如下所示的数组列表:
ArrayList<Individual>[] group = new ArrayList<Individual>()[4];
但它不是编译。我该怎么做呢?
我想创建一个如下所示的数组列表:
ArrayList<Individual>[] group = new ArrayList<Individual>()[4];
但它不是编译。我该怎么做呢?
当前回答
我想我有点晚了,但我遇到了同样的问题,必须按照我的项目的要求创建一个数组列表数组,以便将不同子类的对象存储在同一个地方,这是我最终所做的:
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类型的Array
ArrayList<Integer>[] a = new ArrayList[n];
为数组中的每个元素创建一个数组列表
for(int i = 0; i < n; i++){
a[i] = new ArrayList<Integer>();
}
为了静态地声明一个数组列表数组,例如,精灵位置为Points:
ArrayList<Point>[] positionList = new ArrayList[2];
public Main(---) {
positionList[0] = new ArrayList<Point>(); // Important, or you will get a NullPointerException at runtime
positionList[1] = new ArrayList<Point>();
}
动态:
ArrayList<Point>[] positionList;
int numberOfLists;
public Main(---) {
numberOfLists = 2;
positionList = new ArrayList[numberOfLists];
for(int i = 0; i < numberOfLists; i++) {
positionList[i] = new ArrayList<Point>();
}
}
尽管这里有一些注意事项和一些复杂的建议,但我发现一个数组列表数组是表示相同类型的相关数组列表的一种优雅解决方案。
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<String>[] lists = (ArrayList<String>[])new ArrayList[10];