2012-08-01 100 views
3

我正在循環一些數據,創建每個步驟的ArrayList<ArrayList<Cell>>。每個Cell類別存儲rowcol(等等)。在類之外被修改的私有變量 - Java

我的問題是,當我調查我listOfCells之後,每Cell對象具有相同的行(的myData最後一行。此功能僅row發生,列,因爲他們應該(也就是他們自己惟一的)從我可以告訴,row適當增加,但是當這樣做,我不知道是什麼導致這改變了我的listOfCells

row所有的值。

創建的

Cell
Cell cell = null; 
int row = 0; 
int col = 0; 
ArrayList<Cell> tmpCellList = new ArrayList<Cell>(); 
ArrayList<ArrayList<Cell>> listOfCells = new ArrayList<ArrayList<Cell>>();  

for (ArrayList<double> eachRow : myData) { 
    row++; 
    for (double eachCol : eachRow) { 
     col++; 
     cell = new Cell(); 
     cell.setCol(col); 
     cell.setRow(row); 
     cell.setValue(eachCol); 
     tmpCellList.add(cell); 
    } 
    listOfCells.add(row-1, tmpCellList); 
} 

Cell

public class Cell { 
    private int row; 
    private int col; 
    private double value; 

public void setRow(int rowIn) { 
    this.row = rowIn; 
} 

public int getRow() { 
    return row; 
} 

public void setCol(int colIn) { 
    this.col = colIn; 
} 

public int getCol() { 
    return col; 
} 

    public void setValue(double val) { 
      this.value = val; 
    } 

    public double getValue() { 
      return value; 
    } 
+2

移動你的'ArrayList tmpCellList = new ArrayList ();'在第一個for循環中。 – 2012-08-01 14:09:02

回答

6

你的所有行的都是一樣的ArrayList<Cell>
因此,它們都包含相同的單元格。

您需要爲每行創建一個new ArrayList<Cell>()

+0

謝謝,這是做到了。 – user1568761 2012-08-01 14:17:19