[英]private variables being modified outside of class - Java
I'm looping through some data, creating an ArrayList<ArrayList<Cell>>
of each step. 我正在遍历一些数据,创建每个步骤的
ArrayList<ArrayList<Cell>>
。 Each Cell
class stores a row
and col
(among other things). 每个
Cell
类都存储row
和col
(以及其他内容)。
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
. 我的问题是,当我之后调查我的
listOfCells
,每个Cell
对象都有相同的行( myData
的最后一行。这只发生row
,列就像它们应该的那样(也就是说,它们本身是唯一的)。可以看出, row
正在递增,但是当它正确时,它会更改listOfCells
row
所有值。
I have no idea what's causing this. 我不知道是什么造成了这个。
Cell
's 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
Class 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;
}
All of your rows are the same ArrayList<Cell>
. 您的所有行都是相同的
ArrayList<Cell>
。
Therefore, they all contain the same cells. 因此,它们都包含相同的细胞。
You need to create a new ArrayList<Cell>()
for each row. 您需要为每一行创建一个
new ArrayList<Cell>()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.