i have the following Junit class for testing (tests are not included sinc they are not important in this case):
public class BoardImplTest {
List<Coords> startingCells = new ArrayList<>();
Coords cellCoords = new Coords();
private void addCell(int col, int row){
cellCoords.setCols(col);
cellCoords.setRows(row);
startingCells.add(cellCoords);
}
private void testSetup() {
addCell(3,2);
addCell(4,2);
addCell(1,3);
addCell(2,3);
addCell(3,3);
addCell(4,4);
}
after running is, the array startingCells is filled with only one value:
addCell(3,2);
array has size=1 with one element of coords of (3,2)addCell(4,2);
array has size=2 with two elements of coords of (4,2)addCell(1,3);
array has size=3 with three elements of coords of (1,3)and so on.
after every call of addCell, array increases its size and all fields are filled with values passed as argument, and i want these values only to be added as the last element of Array. Where is the problem?
You're creating a single instance of Coords
, and adding a reference to that single object every time addCell
is called, after mutating it. You should create a new instance of Coords
each time, e.g.
// Remove the cellCoords field
private void addCell(int col, int row) {
Coords cellCoords = new Coords(col, row);
startingCells.add(cellCoords);
}
(That's assuming a sensible Coords
constructor. If there isn't one, you'll need to create an instance and then call setCols
and setRows
... but still you'll be creating a new object each time. If Coords
is under your control, you can make sure that it does have a suitable constructor, and make it more readable as Coordinate
, with column
and row
properties, or even x
and y
... I'd advise making it final and immutable too.)
See more on this question at Stackoverflow