This is my code:
public Move makeMove(int[][] board)
(… more code …)
int[][] nextMove = board.clone();
nextMove[i][j] = 1;
int nextMaxMove = maxMove( nextMove );
System.out.println( next max move: " + nextMaxMove + " " + maxMove( board ) );
the int[][] board is a 8×8 board and I attempt to calculate the best move in a board game.
When I have found a list of equaly good moves I want to check what possibilities the opponent have given the different moves I can do. So I clone() the board, edit the clone nextMove[i][j] = 1 and call the maxMove function on the new board.
the println is for debugging, and I get the same result for maxMove( nextMove ); and maxMove( board ), this is wrong.. It seems like nextMove remain unchanged..
This happens because your data structure is an array of arrays – which, under the hood, is an array of references. Your clone is a shallow copy, so the clone contains the original arrays.
This sample code demonstrates it.
The solution is to explicitly copy the contents of your 2-dimensional array, rather than using
.clone().