I'm looping through some data, creating an ArrayList<ArrayList<Cell>>
of each step. Each Cell
class stores a row
and col
(among other things).
My problem is that when I investigate my listOfCells
afterward, every Cell
object has the same row (the last row of myData
. This only happens with row
, the columns are as they should be (that is, unique to themselves). From what I can tell, row
is incrementing properly, but when it does, it changes all the values of row
in my listOfCells
.
I have no idea what's causing this.
Cell
'sCell 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
Classpublic 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;
}
All of your rows are the same ArrayList<Cell>
.
Therefore, they all contain the same cells.
You need to create a new ArrayList<Cell>()
for each row.