Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

private variables being modified outside of class - Java

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.

Creating Cell's

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

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;
    }
like image 322
user1568761 Avatar asked Mar 27 '26 23:03

user1568761


1 Answers

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.

like image 147
SLaks Avatar answered Mar 31 '26 11:03

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!