Why does Array.copyOf() mutate the original array in case of 2D Arrays?

后端 未结 2 1257
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 13:39

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         


        
2条回答
  •  日久生厌
    2021-01-23 14:12

    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: T[] copyOf(T[], int). 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?

提交回复
热议问题