我正在尝试为我的项目实现ArrayList,但我在途中遇到了一些问题。如果有人能帮助我,那就太好了。
我有这个三维数组的字符串,通过它迭代它以保持一些字符串值。
for(int x=0;x<array.length;x++){
for(int y=0;y<array[0].length;y++){
for(int z=0;z<array[0][0].length;z++){
array[x][y][z] = "Lorem ipsum";
}
}
}
但由于其大小的灵活性,我决定使用ArrayList。
问题是,我不知道如何迭代3维ArrayList。认为这样的事情会起作用,但事实并非如此。
ArrayList<ArrayList<ArrayList<String>>> arrSup = new ArrayList<ArrayList<ArrayList<String>>>();
for(int x=0;x<arrSup.size();x++){
for(int y=0;y<arrSup[0].size();y++){
for(int z=0;z<arrSup[0][0].size();z++){
array[x][y][z] = "Lorem ipsum";
}
}
}
那么,谁能告诉我如何迭代三维ArrayList?
谢谢。
答案 0 :(得分:1)
使用ArrayList::get(int index)
和ArrayList::set(int index, T value)
:
int INITIAL_X_SIZE = 100;
int INITIAL_Y_SIZE = 100;
int INITIAL_Z_SIZE = 100;
ArrayList<ArrayList<ArrayList<String>>> arrSup = new ArrayList<ArrayList<ArrayList<String>>>(INITIAL_X_SIZE);
// Initialize the ArrayLists:
for(int x = 0; x < INITIAL_X_SIZE; x++) {
arrSup.set(x, new ArrayList<ArrayList<String>>(INITIAL_Y_SIZE));
for(int y = 0;y < INITIAL_Y_SIZE; y++) {
arrSup.get(x).set(x, new ArrayList<String>(INITIAL_Z_SIZE));
}
}
// Iterate through it and do whatever you want to do:
for(int x = 0; x < arrSup.size(); x++) {
for(int y = 0; y < arrSup.get(x).size(); y++) {
for(int z = 0; z<arrSup.get(x).get(y).size(); z++) {
array.get(x).get(y).set(z, "Lorem ipsum");
}
}
}
答案 1 :(得分:0)
您需要使用get
没有arrayList的索引。
ArrayList<ArrayList<ArrayList<String>>> arrSup = new ArrayList<ArrayList<ArrayList<String>>>();
for(int x=0;x<arrSup.size();x++){
for(int y=0;y<arrSup.get(0).size();y++){
for(int z=0;z<arrSup.get(0).get(0).size();z++){
array.get(x).get(y).set(z, "Lorem ipsum");
}
}
}
答案 2 :(得分:0)
假设一个10x10x10阵列:
ArrayList<ArrayList<ArrayList<String>>> arrSup = new ArrayList<ArrayList<ArrayList<String>>>();
for (int x = 0; x < 10; x++) {
arrSup.add(new ArrayList<ArrayList<String>>());
for (int y = 0; y < 10; y++) {
arrSup.get(x).add(new ArrayList<String>());
for (int z = 0; z < 10; z++) {
arrSup.get(x).get(y).add("Lorem ipsum");
}
}
}
答案 3 :(得分:0)
与多维数组不同,列表不会为您分配,因此您必须自己添加子列表。
迭代可以通过两种方式完成,具体取决于您是否需要坐标。
// Build matrix
final int SIZE_X = 10;
final int SIZE_Y = 10;
final int SIZE_Z = 10;
List<List<List<String>>> matrix = new ArrayList<>();
for (int x = 0; x < SIZE_X; x++) {
List<List<String>> yList = new ArrayList<>();
matrix.add(yList);
for (int y = 0; y < SIZE_Y; y++) {
List<String> zList = new ArrayList<>();
yList.add(zList);
for (int z = 0; z < SIZE_Z; z++)
zList.add("Lorem ipsum");
}
}
// Iterate matrix without coordinates
for (List<List<String>> yList : matrix)
for (List<String> zList : yList)
for (String value : zList) {
System.out.println(value);
}
// Iterate matrix with coordinates
for (int x = 0; x < matrix.size(); x++) {
List<List<String>> yList = matrix.get(x);
for (int y = 0; y < yList.size(); y++) {
List<String> zList = yList.get(y);
for (int z = 0; z < zList.size(); z++) {
String value = zList.get(z);
System.out.println(value);
}
}
}