Cloning and editing int [] [] in java - cannot change int [] []

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 ) ); 

int[][] board is an 8x8 board, and I'm trying to figure out the best move in a board game.

When I found a list of equal good moves, I want to check what opportunities my opponent gave to other moves that I can make. So, I clone() board , edit the clone nextMove[i][j] = 1 and call the function maxMove on the new board.

println is for debugging, and I get the same result for maxMove( nextMove ); and maxMove( board ) , this is wrong. It appears that nextMove remains unchanged ..

+4
source share
1 answer

This is because your data structure is an array of arrays, which under the hood is an array of links. Your clone is a shallow copy, so the clone contains the original arrays. This sample code demonstrates this.

  int[][] x = new int[][] { { 1,3 }, { 5,7 } }; int[][] copyOfX = x.clone( ); copyOfX[1][1]=13; for ( int i = 0; i < 2; i++ ) { System.out.println(x[i] + "/" + copyOfX[i]); for ( int j = 0; j < 2; j++ ) { System.out.println(x[i][j] + "/" + copyOfX[i][j]); } } 

The solution is to explicitly copy the contents of your two-dimensional array, instead of using .clone() .

+2
source

All Articles