Reputation: 7817
I have a Board class that has the following private variables:
private int[][] table = new int[BOARD_DIMENSION][BOARD_DIMENSION]
private List<Character> movesTaken = new ArrayList<Character>();
private List<Integer> future = new ArrayList<Integer>();
I want to be able to clone a new Board via the following method:
public Board copy(Board parent){
return new Board(parent);
}
public Board(Board parent){
System.arraycopy(parent.getTable(),0,this.table,0,parent.getTable().length);
this.future = parent.getFuture();
this.initialiseTileReps();
this.initialiseValueReps();
this.movesTaken = parent.getMovesTaken();
}
However when I copy a Board object:
Board U = root.copy(root);
(where root is the board I want to copy).
If I modify U U.move('U');
I expect that to modify U's table that contains all the game pieces.
However it also modifies root's table.
Can someone please help me clone my custom Board?
Upvotes: 0
Views: 547
Reputation: 5424
use this :
public Board copy(Board parent){
return new Board(parent);
}
public Board(Board parent){
System.arraycopy(parent.getTable(),0,this.table,0,parent.getTable().length);
this.future = new ArrayList<Character>(parent.getFuture());
this.initialiseTileReps();
this.initialiseValueReps();
this.movesTaken = new ArrayList<Character>(parent.getMovesTaken());
}
Upvotes: 1
Reputation: 32535
Remember that you are in OOP
and array copy copies references not "clones" actual objects. You would have to manually copy objects in your array.
Little bit messy, but 100% functional method for "cloning" objects woulkd be to serialize it, and then deserialize using eg. ObjectOutputStream
and ObjectIntputStream
. This would create deep copy of targeted object. It is possible as far, as every component of your class can be serialized.
Upvotes: 2