开发者

what is shallow copy of array

When you call the clone() method of an Arra开发者_开发技巧yList, a shallow copy of the list is created. what is shallow copy of array?


If you have references in the ArrayList, the same references will be copied into the cloned ArrayList. The objects will not be cloned.


You should distinguish between two kinds of copy: shallow and deep.

While deep copy allocates new space for the whole array and all its content (if it contains references, then new space is allocated to create instances with the same values of the ones copied), shallow copy just allocates space with the same size of the copied array.

Example:

Array A has been allocated to contain only two mutable objects ( e.g.: a list or an arraylist). Do you want to have just a copy of the "extern" array (the one that contains the two references) or do you want a deep copy, that will allocate also new instances of the two references contained in A ?

In the first case, for example:

A is the array starting at reference 0x0000AA

ElementOne starts at 0x00BBCC

ElementTwo starts at 0x00BBFF

If you execute a shallow copy:

B (the new array) will start at reference 0x0000BB, ElementsOne and ElementsTwo will point to the old references (0x00BBCC, 0x00BBFF).

If you execute a deep copy, not only it allocates the new space for the array, but it also allocates space to contain the new instances (a new list, a new arraylist ...).


Only the elements of the array are copied. If they are reference types, only the reference is copied. Any subtypes or elements of the object behind the reference are not copied.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜