0

I need to clone a 2d array of Cell objects but it doesn't work as it should. Whenever i clone the maze, it clones it but when i make changes to one, it is also visible on the other

somebody knows what the problem is???

public void cloneMaze(boolean backup)
{
    if (backup) {
        backupMaze = (Cell[][]) maze.clone();
        for (int i = 0; i < maze.length; i++) {
            backupMaze[i] = (Cell[]) maze[i].clone();
        }
    } else {
        maze = (Cell[][]) backupMaze.clone();
        for (int i = 0; i < backupMaze.length; i++) {
            maze[i] = (Cell[]) backupMaze[i].clone();
        }
    }
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
user3197307
  • 135
  • 1
  • 10
  • 4
    Please show what you mean by "make changes". I suspect you mean "maze[i][j].setFoo(...)" which isn't a change to the array, it's a change to the object which the array refers to. Your copy still isn't *really* deep - for that, you'd need to clone each `Cell` as well. – Jon Skeet Jun 13 '14 at 12:19
  • What are you storing in the maze? Are the objects in the arrays dynamic? – Tim B Jun 13 '14 at 12:19
  • possible duplicate of [Deep copy of an object array](http://stackoverflow.com/questions/3947227/deep-copy-of-an-object-array) – Mena Jun 13 '14 at 12:22
  • The objects in the maze are generated at the beginning of the game and change according to movements etc. – user3197307 Jun 13 '14 at 12:32

1 Answers1

1

In your backup maze, you need to create new Cell that are a copy of the first ones

Otherwise both your mazes point to the same objects, thus modification to the cells are reflected in both mazes.

clone() is just a shallow copy of your array, while you seem to look for deep copy.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118