Reputation: 21
When I copy a 2D array into a different temporary array, it changes my original when I perform operations on the temporary.
Here is a part of my code to show what I mean:
public int getPossibleMoves(int color, int turn) {
int x = 0;
int blankI;
blankI = -1;
int pBoard[][];
pBoard = new int[board.length][board.length];
System.arraycopy(board, 0, pBoard, 0, board.length);
//if its the first turn and color is black, then there are four possible moves
if(turn == 0 && color == BLACK) {
pBoard[0][0] = BLANK;
current.addChild(pBoard);
current.children.get(x).setParent(current);
System.arraycopy(board, 0, pBoard, 0, board.length);
x++;
pBoard[pBoard.length-1][pBoard.length-1] = BLANK;
current.addChild(pBoard);
current.children.get(x).setParent(current);
System.arraycopy(board, 0, pBoard, 0, board.length);
x++;
pBoard[pBoard.length/2][pBoard.length/2] = BLANK;
current.addChild(pBoard);
current.children.get(x).setParent(current);
System.arraycopy(board, 0, pBoard, 0, board.length);
x++;
pBoard[(pBoard.length/2)-1][(pBoard.length/2)-1] = BLANK;
current.addChild(pBoard);
current.children.get(x).setParent(current);
System.arraycopy(board, 0, pBoard, 0, board.length);
x++;
}
On the line that says pBoard[0][0] = BLANK;
and the similar ones, it changes board as well as pBoard
and I need board to stay the same for my program to work correctly.
I have found an answer similar to this, which is where I got the idea to use System.arraycopy()
instead of pBoard = board
. The System.arraycopy()
works in a different program that I used it in, but not in this one.
Any help is greatly appreciated.
One more thing:
This is part of a homework assignment. However, solving this small issue will not even bring me close to the final product that I need. This is just a tiny chunk of my code so far, but I need to get past this to move on.
Upvotes: 2
Views: 2408
Reputation: 65813
You need to do a deep copy.
Instead of:
pBoard = new int[board.length][board.length];
System.arraycopy(board, 0, pBoard, 0, board.length);
Try:
pBoard = new int[board.length][];
for ( int i = 0; i < pBoard.length; i++ ) {
pBoard[i] = new int[board[i].length];
System.arraycopy(board[i], 0, pBoard[i], 0, board[i].length);
}
Upvotes: 3
Reputation: 13525
int board[][]
is array of references to arrays of type int[]
. System.arraycopy(board, 0, pBoard, 0, board.length)
copies the array of references but not the referenced arrays, which now are accessible in two ways. To make deep copy you have to make copies of the referenced one-dimensional arrays also. Note, to make a copy of an array you can use array.clone()
. Consider also to use a one-dimensional array of size N*N with access array[x+N*y]
.
Upvotes: 1