2017-06-10 31 views
0

最近我一直在抨擊的頭這一段代碼:如何停止從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

回答

0

問題在於如何初始化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