如何停止从overwritng变量循环嵌套的ArrayList

问题描述:

最近我一直在抨击的头这一段代码:如何停止从overwritng变量循环嵌套的ArrayList

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,你会看到这一点: All the tiles are on one side

我一直在尝试一些东西,但我通常把覆盖问题,我不想让它变得不必要的复杂和漫长。有谁知道这个问题的解决方案?任何帮助,将不胜感激!

编辑:

我有什么: [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)] ...]

+0

您可以创建一个小的文本部分输出您期望的和一个你所得到的小文本部分?这个图形既小又难以理解。 –

+0

在这里你走Ben! – Trashtalk

+0

当你希望其他行以'(1,0)','(2,0)'开始时,为什么你要第一行从'(0,1)'开始,而不是'(0,0) ,...? – Andreas

问题在于如何初始化this.tiles,你这样做,但可能你只设置了1个arr唉列表,所以实际上你有十倍于同样的价值清单。

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; 
+0

这结束了工作,尽管我仍然没有支持这项工作,我非常感谢。 – Trashtalk