When you assign an array variable to an existing array, you are not getting a new array. You get two references to the same array.
For instance:
int[] a = { 1, 2, 3}; int[] b = a;
a and b are not two arrays, but two references to the same array. Subsequently, the change in a coincides with the change in b .
With 2D arrays, there is another catch: the int[][] x array is actually an array containing a sequence of other arrays. Therefore, a naive copy of it ( int[][] y = x.clone() ) will give you two int[][] arrays containing general references to the sequence of int[] arrays.
To correctly copy a 2D array, you must copy the individual 1D arrays inside it.
-
In your case, both objects contain references to the same array. If you want them to have separate arrays, you need to copy the array. You can copy the array in the constructor as follows:
public Board(int[][] layout) { board = new int[layout.length][]; for (int i = 0; i < layout.length; ++i) { board[i] = layout[i].clone(); } }
source share