Search code examples
javaclonedeep-copy

Overriding the clone method - not working (Java)


I'm writing a search algorithm to solve the 15 puzzle problem in java. When I clone the puzzle states to generate the new possible moves (the daughters) they still alter each other rather than being separate.

Here's my clone method:

public FifteenPuzzleState clone() throws CloneNotSupportedException
{
FifteenPuzzleState copy = (FifteenPuzzleState)super.clone();
for(int i=0; i<copy.currentConfig.length; i++){
    copy.currentConfig[i] = Arrays.copyOf(currentConfig[i], currentConfig[i].length);
}
return copy;     
} 

So my problem is that after I clone the state and then alter it, it will also affect the previous state and all other clones. My first thought was that I didn't create a deep copy of the 2d array properly but I can't find anything wrong with the code above.

Any suggestions? Thanks


Solution

  • You are correct. You need to make a deep copy by manually clone()ing each element in the array.