java.lang.System.arraycopy()是否使用浅表副本? [英] Does java.lang.System.arraycopy() use a shallow copy?
问题描述
System.arraycopy()
是一种浅表复制方法。
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
将为{1,2}现在。 a
中的更改不会影响 b
。
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
将包含 new MyObject(1)
,现在 new MyObject(2)
。但是,如果在 a
中对 new MyObject(1)
进行了任何更改,则会影响 b
。
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.
以上语句是否正确?
推荐答案
以上语句正确与否?
Above statements are correct or not?
是的,您是正确的。
System.arraycopy
总是进行浅表复制,无论数组是否包含引用或原语,例如 int
s或 doubles
s。
System.arraycopy
always does a shallow copy, no matter if the array contains references or primitives such as int
s or doubles
s.
更改数组 a
不会影响数组 b
(当然,除非 a == b
)。
Changes in array a
will never affect array b
(unless a == b
of course).
但是,如果
a
中的新MyObject(1)有任何更改,也会影响b
。
But if any changes of new MyObject(1) in
a
, it will affectb
as well.
取决于您的意思。要挑剔,对新MyObject(1)
的更改不会影响 a
或 b
(因为它们仅包含对对象的引用,并且引用不变)。但是,无论您使用哪个引用来更改对象,该更改都将在 a
和 b
中可见。
Depends on what you mean. To be picky, a change to the new MyObject(1)
will neither affect a
nor b
(since they only contain references to the object, and the reference doesn't change). The change will be visible from both a
and b
though, no matter which reference you use to change the object.
这篇关于java.lang.System.arraycopy()是否使用浅表副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!