Arrays.copyOf会产生浅拷贝还是深拷贝? [英] Does Arrays.copyOf produce a shallow or a deep copy?
问题描述
对于 Arrays.copyOf
是否会产生深或浅,似乎存在很多混淆和不同意见([1]和其他来源)复制。
There seems to be a lot of confusion and different opinions on this out there ([1] and other sources) on whether Arrays.copyOf
will produce a deep or shallow copy.
此测试表明副本很深:
String[] sourceArray = new String[] { "Foo" };
String[] targetArray = java.util.Arrays.copyOf( sourceArray, 1 );
sourceArray[0] = "Bar";
assertThat( targetArray[0] ).isEqualTo( "Foo" ); // passes
此测试表明副本很浅:
String[][] sourceArray = new String[][] { new String[] { "Foo" } };
String[][] targetArray = java.util.Arrays.copyOf( sourceArray, 1 );
sourceArray[0][0] = "Bar";
assertThat( targetArray[0][0] ).isEqualTo( "Foo" ); // fails
解决方案是否只是制作了顶级维度的深层副本,但是其他尺寸是浅版?真相是什么?
Is the solution simply that a deep copy of the top-level dimension is made, but other dimensions are a shallow copy? What is the truth?
[1] How do I do a deep copy of a 2d array in Java?
推荐答案
它生成一个浅拷贝,即包含旧引用的 new 数组(对于相同的对象,不会被复制)。
It produces a shallow copy, i.e. a new array that contains "old" references (to the same objects, those are not being copied).
特别是,如果您有嵌套数组,则不会复制这些数组。您将获得一个新阵列,其顶级指向与原始阵列相同的第二级阵列。这些嵌套数组中的任何更改都将反映在副本和原始数据中。
In particular, if you have nested arrays, those will not be copied. You will just get a new array whose "top level" points to the same "second level" arrays as the original did. Any changes inside those nested arrays will be reflected in both copy and original.
此测试表明副本很深:
This test suggests that the copy is deep:
不,它没有。将新对象分配给原始数组时,这不会影响副本。毕竟,这是一份副本。
No, it does not. When you assign a new object to the "original" array, this does not affect the copy. It is, after all, a copy.
这与以下情况相同:
String x = "foo";
String y = x;
x = "bar";
assertEquals(y, "foo");
此处没有深层复制。
这篇关于Arrays.copyOf会产生浅拷贝还是深拷贝?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!