Part 3 of 6 · 2 min read
Shallow and deep copies
Copying the parts too.
A copy must be a separate object. The danger lies in fields that refer to other objects. A shallow copy copies the fields as they are, so the copy and the original point at the same inner objects. A deep copy also copies the inner objects, so the two are fully separate.
class Attendee { String name; Attendee(String n) { name = n; } }
class MeetingTemplate {
String title; int hours;
List<Attendee> attendees = new ArrayList<>();
MeetingTemplate(String t, int h) { title = t; hours = h; }
MeetingTemplate(MeetingTemplate o) { // deep copy
title = o.title; hours = o.hours;
for (Attendee a : o.attendees) attendees.add(new Attendee(a.name));
}
MeetingTemplate shallow() { // shares the list
MeetingTemplate m = new MeetingTemplate(title, hours);
m.attendees = attendees;
return m;
}
}
Suppose the template lists one attendee, "asha". A shallow copy's first attendee is renamed to "ravi". Printing the original's first attendee then shows "ravi", because both objects share one list and one Attendee. With the deep copy, the same rename leaves the original at "asha".
This is the most common bug with prototypes. A template silently changes whenever a user edits a copy. GoF warns that a composite prototype needs Clone to make a deep copy, so that objects with different structures can serve as prototypes. Immutable parts, such as String, can be shared safely, because they cannot change. Copy only the mutable ones.
Deep copy
A deep copy duplicates an object and all the mutable objects it refers to, so that changing the copy cannot change the original.
Example: a template copy with its own attendee list and its own Attendee objects.
Check yourself: 1. What is shared in a shallow copy? 2. Which parts of an object can be shared safely in a deep copy?