Does java.lang.System.arraycopy() use a shallow copy?
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 开发者_Python百科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?
Above statements are correct or not?
Yes, you are correct.
System.arraycopy
always does a shallow copy, no matter if the array contains references or primitives such as int
s or doubles
s.
Changes in array a
will never affect array b
(unless a == b
of course).
But if any changes of new MyObject(1) in
a
, it will affectb
as well.
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.
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 array b
).
精彩评论