Question

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?

Was it helpful?

Solution

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 ints, null, and an array of no ints.

(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].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top