I have a 2d array of of type ChessPiece[][]
. I need a copy of it to make modifications but the value of the objects are passed by reference because they're changing when I copy the original array and make modifications.
Here is the code I am using.
public static ChessPiece[][] copyChessBoard() {
ChessPiece[][] resultArray = new ChessPiece[currentBoardState.length][];
for (int i = 0; i < currentBoardState.length; i++) {
ChessPiece[] pieces = currentBoardState[i];
int len = pieces.length;
resultArray[i] = new ChessPiece[len];
System.arraycopy(pieces, 0, resultArray[i], 0, len);
}
return resultArray;
}
I took this code from another stack overflow question and applied it to my situation. It appears the the array is passed by value but the objects that the array contains are passed by reference I think. Any help is appreciated
EDIT: Attempt at answer.
So say I create a new "copy" method like so:
public ChessPiece copyChessPiece() {
ChessPiece piece = new ChessPiece(Color.BLACK) //original constructor
piece.x = this.x;
piece.y = this.y;
piece.possibleMoves = this.possibleMoves;
piece.side = this.side;
return piece;
}
Then would my final code for copying the full array have to look like this?
public static ChessPiece[][] copyChessBoard() {
ChessPiece[][] resultArray = new ChessPiece[currentBoardState.length][];
for (int i = 0; i < currentBoardState.length; i++) {
ChessPiece[] pieces = currentBoardState[i].copyChessPiece();
int len = pieces.length;
resultArray[i] = new ChessPiece[len];
System.arraycopy(pieces, 0, resultArray[i], 0, len);
}
return resultArray;
}