Does java.lang.System.arraycopy() use a shallow copy?

末鹿安然 提交于 2019-12-10 11:54:44

问题


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?


回答1:


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 ints or doubless.

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 affect b 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.




回答2:


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).



来源:https://stackoverflow.com/questions/6101684/does-java-lang-system-arraycopy-use-a-shallow-copy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!