Sunday, 11 March 2018

java - Cloning multi-dimensional arrays



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?


Answer




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


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...