Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

java - Changes in the copy of a 2-D array produced via Arrays.copyOf() reflect in the the original array

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}}
c1 ==> int[2][] { int[2] { 1, 2 }, int[2] { 3, 4 } }

jshell> int[][] d1 = Arrays.copyOf(c1, c1.length)
d1 ==> int[2][] { int[2] { 1, 2 }, int[2] { 3, 4 } }

If I then change an element in the copy, why does the corresponding cell in the original 2D array get mutated in the process?

jshell> d1[0][0] = 0
$21 ==> 0

jshell> d1
d1 ==> int[2][] { int[2] { 0, 2 }, int[2] { 3, 4 } }

jshell> c1
c1 ==> int[2][] { int[2] { 0, 2 }, int[2] { 3, 4 } } // c1[0][0] was 1 originally

This leads me to believe that during a copy of 2D arrays using Arrays.copyOf(), a separate copy is created only for the outermost array, while each inner array is still a reference to the inner arrays of the original 2D array?

jshell> d1 = null
d1 ==> null

jshell> c1
c1 ==> int[2][] { int[2] { 0, 2 }, int[2] { 3, 4 } }

If so, why is it this way? Shouldn't Arrays.copyOf() create distinct copies, at least per the docs? Is this behavior documented anywhere in the Oracle docs?

Lastly, what is the correct way to create distinct copies of a 2D array, the same way Arrays.copyOf() works for 1D arrays?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...