So I'm trying to build a searchtree that has 2d arrays of enums in each node. So I have this board class which has a 2d array of my Cells enum. I loop through this cell array to find possible moves and when one is found, I want to store the current state of the 2d array in the tree. Each time I find this move, I want to change the status of some of the enums in that enum and put that in the tree and then continue looking for more moves. Now the problem occurs when I flip these moves beacuse it seem to affect every 2d array even though they are not the same object! Down below is some PsudoCode mixed with my real code to show the essentials: TreeBuilder.Java
When move is found
board.Flip(coordinates, color);
tree.add(new Board(board.getCells()));
Board.Java
public void flipDiscs(List<int[]> coordinates, Cell colorToChangeTo) {
for (int[] discCoordinate : coordinates) {
this.cells[discCoordinate[0]][discCoordinate[1]] = colorToChangeTo;
}
}
public Board(Cell[][] cells) {
this.cells = Arrays.copyOf(cells, cells.length);
}
Whenever I do this, all cell arrays get changed thus resulting in the wrong state. Here is an image of the debugger after running this code:
I created an example just for testing the Arrays.copyOf method and it works as expected:
private enum LigthSwitch{
On,
Off
}
public static void main(String[] args) {
LigthSwitch[] firstFloor = new LigthSwitch[]{LigthSwitch.On, LigthSwitch.On};
LigthSwitch[] secondFloor = new LigthSwitch[]{LigthSwitch.On, LigthSwitch.On};
LigthSwitch[] thirdFloor = Arrays.copyOf(firstFloor, firstFloor.length);
secondFloor[0] = LigthSwitch.Off;
}
Running this code results in just that secondFloor[0] == LightSwitch.Off
as expected.