If I create a 2D int
array in Java, and then make a copy of it using Arrays.copyOf()
, like so -
jshell> int[][] c1 = {{1,2}, {3,4}}
c
A 2D array is basically an array that contains arrays, and Arrays.copyOf
does a shallow copy, so only the outer array (the array of arrays) is copied, not the values inside the array (in this case, arrays of int
, ie int[]
). As a result, both the original and the copy contain the same int[]
arrays, so if you modify through one, the result is also visible through the other.
This is explicitly mentioned in the javadoc:
For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.
You do need to read that with the knowledge of the signature:
. The array copied is T[]
(an array of T
, where T
is int[]
), not T[][]
!
For a deep copy of a 2D array, you will have to deep copy the array yourself, for example see How do I do a deep copy of a 2d array in Java?