我想创建一个如下所示的数组列表:
ArrayList<Individual>[] group = new ArrayList<Individual>()[4];
但它不是编译。我该怎么做呢?
我想创建一个如下所示的数组列表:
ArrayList<Individual>[] group = new ArrayList<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。
其他回答
为了静态地声明一个数组列表数组,例如,精灵位置为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>();
}
这种情况的问题是,通过使用数组列表,在特定位置进行加法,你会得到o(n)的时间复杂度。如果使用数组,则通过声明数组来创建内存位置,因此它是常量
根据Oracle文档:
不能创建参数化类型的数组
相反,你可以这样做:
ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);
正如Tom Hawting - tackline所建议的那样,更好的做法是:
List<List<Individual>> group = new ArrayList<List<Individual>>(4);
创建和初始化 对象[]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);