What is a shallow copy of the array

When you call the clone () method on an ArrayList, a shallow copy of the list is created. what is a shallow copy of an array?

+7
c #
source share
3 answers

You must distinguish between two types of copies: shallow and deep .

While a deep copy allocates a new space for the entire array and all its contents (if it contains links, then a new space is allocated for creating instances with the same values โ€‹โ€‹of the copied), a shallow copy simply allocates space with the same size of the copied array.

Example:

Array A was allocated to contain only two mutable objects (for example: a list or arraylist), you want to have only a copy of the "extern" array (one that contains two links), or you need a deep copy that will also highlight new instances of the two links contained in A?

In the first case, for example:

A is an array starting with reference 0x0000AA

ElementOne starts at 0x00BBCC

ElementTwo starts at 0x00BBFF

If you do a shallow copy:

B (new array) starts at 0x0000BB, ElementsOne and ElementsTwo will point to old links (0x00BBCC, 0x00BBFF).

If you are doing a deep copy, it not only allocates new space for the array, but also allocates space for storing new instances (new list, new arraylist ...).

+4
source share

If you have links in an ArrayList, the same links will be copied to the cloned ArrayList. Objects will not be cloned.

+5
source share

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

+3
source share

All Articles