Cloning multi-dimensional arrays

java

Solution

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.)

Problem

``` 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?

Original source

Related problems