Shallow vs Deep Copy (with examples)
- A shallow copy shares its children with the original
- A deep copy has its own copies of the children
The above example showed an object graph. Same story for arrays.
If there are no children?
Since the concept of deep vs shallow concerns treatment of children, it’s meaningless to talk about deep vs shallow copying of objects (or arrays) that doesn’t have any children. When creating a copy of an array of integers for example, the copy can be viewed as both shallow and deep.
pointerA = pointerB?
When you do
pointerA = pointerB no object is copied (so it’s neither a deep nor a shallow copy). A pointer value is copied and you could argue that this is a shallow copy, since the object it points at is not copied.
Mixed copies are part shallow, part deep. If you for instance make shallow copies of the children, then the original and the copy may share the same “grand children”. You could say that the copying is “one level deep”. Another type of mixed copy would be if you create copies of some children, while sharing others. If you for example have a reference to a singleton, or an immutable object it doesn’t make sense to clone these objects.