java.lang.System.arraycopy() 是否使用浅拷贝?
System.arraycopy()
是浅复制方法。
对于原始类型的数组,它将把值从一个数组复制到另一个数组:
int[] a = new int[]{1,2};
int[] b = new int[2];
System.arraycopy(a, 0, b, 0, 2);
b
现在将为 {1,2}。 a
中的更改不会影响 b
。
对于非基本类型的数组,它将把对象的引用从一个数组复制到另一个数组:
MyObject[] a = new MyObject[] { new MyObject(1), new MyObject(2)};
MyObject[] b = new MyObject[2];
System.arraycopy(a, 0, b, 0, 2);
b
将包含 new MyObject(1)
的引用,现在new MyObject(2)
。但是,如果 a
中的 new MyObject(1)
发生任何更改,它也会影响 b
。
上述说法正确与否?
System.arraycopy()
is a shallow copy method.
For an array of a primitive type, it will copy the values from one array to another:
int[] a = new int[]{1,2};
int[] b = new int[2];
System.arraycopy(a, 0, b, 0, 2);
b
will be {1,2} now. Changes in a
will not affect b
.
For an array of a non-primitive type, it will copy the references of the object from one array to the other:
MyObject[] a = new MyObject[] { new MyObject(1), new MyObject(2)};
MyObject[] b = new MyObject[2];
System.arraycopy(a, 0, b, 0, 2);
b
will contain a reference of new MyObject(1)
, new MyObject(2)
now. But, if there are any changes to new MyObject(1)
in a
, it will affect b
as well.
Are the above statements correct or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您是对的。
System.arraycopy
始终进行浅复制,无论数组是否包含引用或基元,例如int
或doubles.
数组
a
中的更改永远不会影响数组b
(当然,除非a == b
)。取决于你是什么意思。需要挑剔的是,对
new MyObject(1)
的更改既不会影响a
也不会影响b
(因为它们只包含引用< /em> 到对象,并且引用不会改变)。不过,无论您使用哪个引用来更改对象,从a
和b
都可以看到更改。Yes, you are correct.
System.arraycopy
always does a shallow copy, no matter if the array contains references or primitives such asint
s ordoubles
s.Changes in array
a
will never affect arrayb
(unlessa == b
of course).Depends on what you mean. To be picky, a change to the
new MyObject(1)
will neither affecta
norb
(since they only contain references to the object, and the reference doesn't change). The change will be visible from botha
andb
though, no matter which reference you use to change the object.只要您专门修改对象的属性并调用对象的方法,您就是正确的。
如果您更改引用点的位置,例如使用
a[0] = new MyObject(1)
,那么即使对象是使用相同的初始化数据创建的,它们现在也将指向不同的实例该对象以及对一个实例的更改不会在另一引用(在数组b
中)中看到。You're correct as long as you're specifically modifying properties and calling methods on your objects.
If you change where the reference points, for example with
a[0] = new MyObject(1)
, then even though the objects were created with the same initialization data, they will now point to different instances of the object and a change to one instance will not be seen in the other reference (in arrayb
).