Reputation: 641
I am having a problem understanding the clone method in Java.
In this example the output is 1.
int[][]x = {{1,2},{3,4}};
int[][]y = new int[2][];
y[0] = x[0].clone();
y[1] = x[1].clone();
x[0][0] = 0;
System.out.println(y[0][0]);
In this example the output is 100 8
int[][][] x = {{{1,2},{3,4}},{{5,6},{7,8}}};
int[][][] y = new int[2][2][];
y[0] = x[0].clone();
y[1][1] = x[1][1].clone();
x[0][0][0] = 100;
x[1][1][1] = 200;
System.out.println(y[0][0][0]+" "+y[1][1][1]);
Why does the value for the y array change in the second example but not the first?
Upvotes: 2
Views: 75
Reputation: 83235
Good question.
To understand this, you must understand (1) what a multidimensional array is in Java, and (2) that clone()
is "shallow".
I'm going to start use 2D arrays in these examples, because they are a little simpler.
(1) A 2D array in Java is an array of arrays.
int[][] a = new int[4][];
a[0] = new int[1];
a[1] = new int[8];
a[3] = new int[0];
This is an array of four arrays of ints
: an array of 1 int
, an array of 8 int
s, null
, and an array of no int
s.
(2) Now, clone()
does a shallow copy. That means that it creates a copy of the array (or object) with the same elements, but the elements of that copied array (or object) are the same as the original.
That means that if I have
int[][] b = a.clone();
then b
is a different array than a
, with the same elements. If I do a[0] = new int[45]
, then b
is unaffected.
Remember, however, that the elements of b
are the same as the elements of a
. So if I do
a[0][0] = 1
that affects b[0]
, since a[0]
and b[0]
are the same array in memory.
Now, what about your case?
int[][]x = {{1,2},{3,4}};
int[][]y = new int[2][];
y[0] = x[0].clone();
y[1] = x[1].clone();
You essential do a "2-deep" clone on a 2D array. That is, x
and y
are different. And x[0]
and y[0]
are different. But x[0][0]
and y[0][0]
are the same in memory. But, oh, it looks like that is just an int
, and you can't mutate an int
, like you could an array.
In the second example, you do essentially do a 2-deep clone on a 3D array. You can (and do) mutate x[0][0]
, which is the same as y[0][0]
.
Upvotes: 3