int[][] array = new int[][] {...}
int[][] clone = array.clone();
I naively expected this to work. But it didn't - it cloned only the first dimension, and I had to go and clone the other dimension manually if I wanted a true clone. Note: the contents were properly copied. But when I changed clone[0][1]
, it reflected in array[0][1]
And while .clone()
is known to perform a shallow clone, int[][]
looks like a single object (if we don't know its internal implementation, at least)
Why is that behaviour chosen? Isn't int[][]
referencing an array object, rather than just the first dimension of the array? And in what scenarios is cloning only the first dimension the desired behaviour?
clone does a "shallow" copy. That is, the outermost array is duplicated, but the values stored in it are unchanged. So if you have A1 = { B1, B2, B3 } and clone that into A2, A2's initial contents will be { B1, B2, B3 }.
A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.
Iterating each element of the given original array and copy one element at a time. Using clone() method. Using arraycopy() method. Using copyOf() method of Arrays class.
Multidimensional arrays are an extension of 2-D matrices and use additional subscripts for indexing. A 3-D array, for example, uses three subscripts. The first two are just like a matrix, but the third dimension represents pages or sheets of elements.
Why is that behaviour chosen?
Consistency, most likely.
As you say, int[][]
references an array object. It just so happens that the contents of each array element is another array, but that's just a detail. Java clones all arrays identically, and since the elements can be of any type it can't guarantee to perform a deep copy.
Hence clone()
for arrays performs a shallow copy, so only the first dimension is cloned.
(In general it doesn't seem that there's a single "best" or "obvious" answer to the question of whether a clone implies deep or shallow copies. What the developer wants will depend on how each field is being used by the application, so a one-size-fits-all approach will naturally have limitations.)
This behavior is demonstrated because there is no true multi dimensional array.
Java achieves multiple dimensions by making arrays of arrays. Which means:
int[][] is actually Array<Array<int>>
Hence the clone would only copy the first dimension.
If you were trying with a 3 dimensional array, you would need to clone thrice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With