I have read many posts about copy constructors but I just can't seem to get it to work. I call the copy constructor but the object still modifies the original:
public class Board {
private Square[][] board = getEmptyBoard();
public Board() {
}
public Board(Board originalBoard) {
Square[][] matrix = new Square[6][6];
for(int row = 0; row <= 5; row++) {
for(int col = 0; col <= 5; col++) {
matrix[row][col] = originalBoard.getSquare(row, col);
}
}
this.board = matrix;
}
[...]
}
The class models a six-by-six board of type Square
. A Square
is an object that can hold one or more objects of type Piece
.
How can I take my original board and make and exact copy of it so that I can add and remove the Piece
s from the Square
s without touching the original Board
objects?
Your deep copy isn't going deep enough. You've created your own 2D
Square
array, but the array is referring to the sameSquare
objects asoriginalBoard
is.You'll need to make a copy of the
Square
object that you're getting fromoriginalBoard
. Depending on what theSquare
object holds, you'll need to make copies of its attributes (e.g.Piece
) in a copy constructor.