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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…