Shallow and Deep Copies

Copying an object matters whenever you want a second version that you can change without accidentally changing the first. A saved game, an editable document draft or a simulation snapshot may contain references to other objects. To predict whether those versions are independent, trace both the outer object and the nested objects its fields identify. The number of variables alone does not tell you how many objects exist.

Assignment and copying

In Java, an object variable holds a reference. Assigning b = a copies that reference. Both variables then identify the same outer object; assignment has not created another instance.


A shallow copy creates a new outer object and copies its field values. Primitive values, such as an int, are copied directly. A reference-valued field also has its value copied, so the new field identifies the same nested object as the original field.


A deep copy creates a new outer object and duplicates the nested mutable objects required by the copying policy. Its purpose is to let those copied objects change independently of the originals. The copying policy should state how far copying extends and which objects may remain shared.


Operation

Outer object

Nested mutable objects

Reference assignment

Same object

Same objects

Shallow copy

New object

References remain shared

Deep copy

New object

Duplicated within the stated copy boundary



Trace field changes separately

Suppose a Report contains an integer field count and a reference field box. The referenced Box contains an integer value. A shallow copy has its own count field and its own box field, but both reports initially identify the same box.


Original and shallow outer objects point to one shared mutable object, while the deep outer object points to a separate mutable object.


Example: The original report has count = 12 and its box has value = 18. After making a shallow copy, setting copy.count = 22 leaves the original count at 12. Setting copy.box.value = 27 changes the shared box, so reading original.box.value now gives 27.


Now consider copy.box = new Box(). This replaces the reference stored in the copied report. It does not replace the original report's reference or change the old box. The distinction is between changing a field of a shared object and replacing a reference to that object.



Choose the required depth

A shallow copy can be sufficient when you only replace outer fields, or when the referenced objects cannot be changed. For example, Java strings are immutable: sharing a string does not allow either copy to alter its contents. Assigning a different string to one outer object's field changes only that field.


A deep copy is useful when you need to edit nested mutable data independently. It requires more allocation and a clear boundary. Copying one level of a nested structure does not automatically copy every deeper level.


Internal sharing also matters. Two fields might identify one nested object. A graph-preserving copy keeps that relationship inside the duplicate: both copied fields identify one new nested object. For a policy that duplicates every reachable mutable object exactly once, counting only those model objects gives


Nnew=Ndistinct reachable mutable objects.N_{\text{new}} = N_{\text{distinct reachable mutable objects}}.


Repeated references do not add objects to that count. If references form a cycle, a copying procedure needs a record of objects already copied. Otherwise, following references recursively may continue indefinitely. Record a new object's counterpart before following its outgoing references so later visits can reuse it.

What to remember

  • Assignment creates another reference to the same outer object.
  • A shallow copy separates the outer object while sharing referenced objects.
  • A deep copy duplicates the mutable state required by its stated policy.
  • Trace field replacement separately from mutation, and account for repeated references and cycles.

Example: Copying a sensor record

A monitoring program stores a sensor record in a Packet. Each packet has an integer field number and a reference field reading. A Reading has an integer field value. All fields are accessible, and the classes have no other fields.


The program creates a shallow copy by copying the original packet's field values into a new packet. It creates a deep copy by also allocating and populating a separate reading. Execute the following setup once; parts b) and c) then continue in order.


Java
Packet original = new Packet();
original.number = 8;
original.reading = new Reading();
original.reading.value = 40;

Packet shallow = new Packet();
shallow.number = original.number;
shallow.reading = original.reading;

Packet deep = new Packet();
deep.number = original.number;
deep.reading = new Reading();
deep.reading.value = original.reading.value;


a) Count the copy allocations

How many new Packet and Reading objects are allocated by the two copying operations, excluding the original packet and its original reading?


First count the outer copies. The assignments using new Packet() for shallow and deep allocate 2 new packets. Assigning primitive fields and existing references does not allocate additional model objects.


Next count nested allocations during copying. The shallow operation reuses the original reading. Only the deep operation uses new Reading(), so the number of newly allocated readings is 1.


Adding the two categories gives


Nnew=2+1=3.N_{\text{new}} = 2 + 1 = 3.


The copying operations allocate 3 new model objects: 2 packets and 1 reading.

b) Mutate the shallow copy

The program now executes the following statements. Find original.number, original.reading.value and deep.reading.value afterward.


Java
shallow.number = 13;
shallow.reading.value = 75;


First locate the integer field being assigned. shallow.number belongs to the new shallow packet, so assigning 13 changes only that packet. The original packet's number remains 8.


Next follow the reading reference. shallow.reading and original.reading identify the same reading object. Assigning 75 to its value is therefore visible through the original packet as well.


Finally examine the deep copy. Its reading is a separate object, and neither statement reaches it. Its value remains the copied initial value, 40. A nested mutation follows the reference to its target object.


The final values are original.number = 8, original.reading.value = 75 and deep.reading.value = 40.

c) Replace the shallow copy's reference

Continuing from part b), the program executes the following statements. Find the reading values now observed through original, shallow and deep.


Java
shallow.reading = new Reading();
shallow.reading.value = 60;


First allocate a new reading and store its reference in the shallow packet. This replaces only shallow.reading. The original packet still identifies the previous reading, whose value became 75 in part b).


Next assign 60 through the shallow packet's replacement reference. This reaches the newly allocated reading rather than the original reading. The deep packet still identifies its own separate reading, which remains at 40.


The observed values are 75 through original, 60 through shallow and 40 through deep. Replacing a reference in one outer object does not replace the corresponding reference in another outer object.

A Java Record has an integer field number and a reference field reading identifying a mutable Reading object. Which procedure creates a shallow copy of an existing record?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A team is testing a graph-preserving deep-copy function for editable documents. Its copy contract specifies which relationships the result must preserve and which objects must become independent. Match each verification criterion to the test that checks it. Object identity means being the very same object, rather than merely holding equal values.

Match each term
A.

Confirm that the returned document is a different object from the input document.

B.

Record all input field values and references before copying and confirm that the copying operation leaves them unchanged.

C.

Edit a mutable note reached through the returned document and confirm that the corresponding input note does not change.

D.

Start with two input fields referring to one mutable note and confirm that the corresponding result fields refer to one replacement note.

Internal sharing preservation

Root independence

Source graph preservation

Nested independence

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A Java program uses a Reading class with an integer field value and a Record class with integer field label and reference field reading. All shown fields are accessible. After this code finishes, complete the table with the final values of label and reading.value for each record. Enter exact integers.


Java
Reading r = new Reading();
r.value = 21;
Record a = new Record();
a.label = 34;
a.reading = r;

Record b = new Record();
b.label = a.label;
b.reading = a.reading;

Record c = new Record();
c.label = a.label;
c.reading = new Reading();
c.reading.value = a.reading.value;

b.label = 55;
b.reading.value = 89;
c.reading.value = 144;
Recordlabelreading.value
a
b
c

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice