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
Example: Shallow copy

Car make: BMW engine: gearbox: Gearbox gears: 6 Engine cylinders: 12 Car make: BMW engine: gearbox:
Example: Deep copy

Car make: BMW engine: gearbox: Gearbox gears: 6 Engine cylinders: 12 Car make: BMW engine: gearbox: Gearbox gears: 6 Engine cylinders: 12

Arrays

The above example showed an object graph. Same story for arrays.

Example: Shallow copy of an array

Person age: 30
Example: Deep copy of an array

Person age: 30 Person age: 30

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.

Example: A shallow, and at the same time deep, copy of an array of primitive values

15 17 3 55 20 15 17 3 55 20

What about pointerA = pointerB?

When you do pointerA = pointerB you’re just copying a pointer value, so no object is copied. Neither deep nor shallow. You could say that it’s a shallow copy of the pointer value, since the object it points at is not copied.

Comments