Java - Implement deep and shallow copy of an array

一曲冷凌霜 提交于 2019-12-05 03:18:41

I am trying to understand the concept of shallow vs deep copy in Java.

In Java you pass around and store references to objects not the objects themselves.
So when you have an NameValue[] array the array does not contain the objects NameValue but references to the objects.
So when you do a shallow copy to NameValue[] array2 it means you are just copying the references from one array to the other. Which effectively means that now both array and array2 refer to exactly the same objects and any change you do from array[2] will be visible from array2[2] (same object).

When you deep copies you copy each object completely to another memory area and you keep a reference to that new object in your new array.
This way the 2 arrays now refer to different objects and any change to array[2] are not visible from array2[2]

Update:
This does not apply to primitives that do store the actual value and not a reference.
So an int[] a when you copy you get a copy of the values (i.e. deep copy in a sense) because a[2] contains the value itself and not the reference to the value.

I don't know where you read that copyOf() performs a deep copy, because that is just plain wrong.

Quoting javadoc of Arrays.copyOf(T[] original, int newLength):

For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.

That means it's a shallow copy. To be a deep copy, the values would have to point to different objects, since the referenced object would have to be a copy too.

To perform a deep copy, you have to iterate the array and copy the values. Java can't do that for you, because it doesn't know how to copy the object.

E.g. how would Java know how to copy a NameValue object? clone()? Copy constructor? Serialize+Deserialize? Factory method? Other means?

Gherbi Hicham

I think there is a little missunderstanding that Arrays.copyOf() produces a deep copy.

Arrays.copyOf() makes a new array that contains old refrences to objects that are not being copied and as the link that I've added explains in the case of nested arrays they will not get copied and hence it can't be considered a deep copy but a shallow copy.

See this for more information.

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