ganjan
ganjan

Reputation: 7576

cloning and editing int[][] in java - not able to 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 )  );

the int[][] board is a 8x8 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..

Upvotes: 4

Views: 115

Answers (1)

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.

    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 2-dimensional array, rather than using .clone().

Upvotes: 2

Related Questions