Java copy constructor not working

714 views Asked by At

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 Pieces from the Squares without touching the original Board objects?

2

There are 2 answers

0
rgettman On BEST ANSWER

Your deep copy isn't going deep enough. You've created your own 2D Square array, but the array is referring to the same Square objects as originalBoard is.

You'll need to make a copy of the Square object that you're getting from originalBoard. Depending on what the Square object holds, you'll need to make copies of its attributes (e.g. Piece) in a copy constructor.

0
Marcos Vasconcelos On

Since you are using Objects (Square) instead of primitives, by associating matrix[row][col] = originalBoard.getSquare(row, col); you are getting the reference of your object, any modification will change both references.

If you want to copy the exact state and modify then you should implements Cloneable at your Square class and call the clone() when associating to the copy array.