2

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;
    }
Ogen
  • 6,499
  • 7
  • 58
  • 124
  • 1
    Yes. Because they are objects (instead of primitives), you have to use `clone()` or create a new instance of them to pass their contents by value. – Nathan Merrill Nov 28 '13 at 02:45
  • 1
    As @MrTi says. Also, consider defining a deepcopy method for your objects. – RaymondMachira Nov 28 '13 at 02:47
  • OK I made an attempt at defining a deepcopy method in my edit, if there's any mistakes please feel free to let me know :) – Ogen Nov 28 '13 at 02:53

1 Answers1

1

There is an Object method called clone(), which returns a clone of that instance, but with a different reference. That would theoretically work. However, clone is not very predictable, and ideally should be overridden within the class. For a general discussion about instance copying, see this.

Edit: In response to your update- you have to make sure that you're not copying references. So if the fields x, y, possibleMoves, and side are primitives, this will work fine. If not, you'll have the same issue as before.

Community
  • 1
  • 1
Sherz
  • 568
  • 2
  • 14