0

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.

  • 1
    *"I created an example just for testing the Arrays.copyOf method and it works as expected:"* - Of course it does, it creates a ___shallow___ copy of the array, as expected. Now I wonder why you think it creates a ___deep___ copy of your 2d array. – Tom Sep 06 '17 at 17:10
  • Beacuse I read it would here on SO. But I'm still using different objects as of my understanding. – checkerNecker1 Sep 06 '17 at 17:15
  • No, it creates a copy of the "lowest" array. Which contains references to the inner arrays, therefore your inner arrays are shared. – Kayaman Sep 06 '17 at 17:21
  • Oh well, that explains it then! Just took 2 hours to find out. :D – checkerNecker1 Sep 06 '17 at 17:24

0 Answers0