如何停止循环覆盖嵌套 ArrayLists 中的变量
How to stop for loops from overwritng variables in nested ArrayLists
最近被这段代码撞得头破血流:
for(int i = 0; i < cols; i++) {
for(int j = 0; j < rows; j++) {
SqrTileNormal temp = new SqrTileNormal(i, j, this, ID.Tile);
setTile(temp);
}
}
//additional info
public void setTile(Tile tile) {
int xPosGrid = tile.getXPosGrid();
int yPosGrid = tile.getYPosGrid();
System.out.println("Coords: (" + xPosGrid + ", " + yPosGrid + ")");
this.tiles.get(xPosGrid).set(yPosGrid, tile);
}
//how the nested array looks like.
protected List<ArrayList<Tile>> tiles;
它是构造函数的一部分,应该用 SqrTileNormal
填充二维数组。我发现了问题所在:for 循环的每次迭代都会不断重写之前的迭代,因此它们最终都以相同的 xPosGrid
结束,您会看到:
我一直在尝试一些事情,但我通常会保留覆盖问题,我不想让它不必要地复杂和冗长。有谁知道这个问题的解决方案?如有任何帮助,我们将不胜感激!
编辑:
我有:
[[null, null, null...][null, null, null...][(null, null, null...]
我想要的:
我得到的:
[[(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)...][(10, 0 ),(10, 1),(10, 2)]...]
问题在于你如何初始化 this.tiles
,你没有展示你是如何做到的,但可能你只设置了 1 个数组列表,所以实际上你有十倍相同的值列表。
您的 this.tiles
init 应该如下所示:
private static List<List<Tile>> getListOfLists() {
int numcol = 5;
int numrow = 5;
List<List<Tile>> bidiArray = new ArrayList<>();
for (int i = 0; i < numcol; i++) {
List<String> sublist = new ArrayList<>();
bidiArray.add(sublist);
for (int j = 0; j < numrow; j++) {
sublist.add(null);
}
}
return bidiArray;
}
但实际上,处理固定数量的列和行我宁愿使用数组,例如:
Tile[][] bidiArray = new Tile[numcol][numrow];
然后这样设置:
this.tiles[xPosGrid][yPosGrid]= tile;
最近被这段代码撞得头破血流:
for(int i = 0; i < cols; i++) {
for(int j = 0; j < rows; j++) {
SqrTileNormal temp = new SqrTileNormal(i, j, this, ID.Tile);
setTile(temp);
}
}
//additional info
public void setTile(Tile tile) {
int xPosGrid = tile.getXPosGrid();
int yPosGrid = tile.getYPosGrid();
System.out.println("Coords: (" + xPosGrid + ", " + yPosGrid + ")");
this.tiles.get(xPosGrid).set(yPosGrid, tile);
}
//how the nested array looks like.
protected List<ArrayList<Tile>> tiles;
它是构造函数的一部分,应该用 SqrTileNormal
填充二维数组。我发现了问题所在:for 循环的每次迭代都会不断重写之前的迭代,因此它们最终都以相同的 xPosGrid
结束,您会看到:
我一直在尝试一些事情,但我通常会保留覆盖问题,我不想让它不必要地复杂和冗长。有谁知道这个问题的解决方案?如有任何帮助,我们将不胜感激!
编辑:
我有: [[null, null, null...][null, null, null...][(null, null, null...]
我想要的:
我得到的: [[(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)...][(10, 0 ),(10, 1),(10, 2)]...]
问题在于你如何初始化 this.tiles
,你没有展示你是如何做到的,但可能你只设置了 1 个数组列表,所以实际上你有十倍相同的值列表。
您的 this.tiles
init 应该如下所示:
private static List<List<Tile>> getListOfLists() {
int numcol = 5;
int numrow = 5;
List<List<Tile>> bidiArray = new ArrayList<>();
for (int i = 0; i < numcol; i++) {
List<String> sublist = new ArrayList<>();
bidiArray.add(sublist);
for (int j = 0; j < numrow; j++) {
sublist.add(null);
}
}
return bidiArray;
}
但实际上,处理固定数量的列和行我宁愿使用数组,例如:
Tile[][] bidiArray = new Tile[numcol][numrow];
然后这样设置:
this.tiles[xPosGrid][yPosGrid]= tile;