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(); } } } 
4
  • 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. Commented Jun 13, 2014 at 12:19
  • What are you storing in the maze? Are the objects in the arrays dynamic? Commented Jun 13, 2014 at 12:19
  • possible duplicate of Deep copy of an object array Commented Jun 13, 2014 at 12:22
  • The objects in the maze are generated at the beginning of the game and change according to movements etc. Commented Jun 13, 2014 at 12:32

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

but how do i copy them to a new Cell?
You can have a constructor copy in Cell like Cell(Cell cell), add a clone() method, or simply create a new Cell() and setting all its attributes properly.
doesnt work with the new Cell method. I set the attributes according to the other cell attributes but doesnt make a diffrence
You need to replace the old Cell reference with the reference to the new Cell. For instance myCell = new Cell(myCell);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.