Java Design Program · CD03
Deep Copy vs Shallow Copy in Java
A shallow copy duplicates the outer object but shares its inner objects. Change a shared list through the copy, and the original changes too.
Problem Statement
A Team has a name and a list of members. Write a copy operation so that adding a member to the copy never changes the original team.
Show the problem with a shallow copy first, then fix it with a deep copy.
Input/Output Examples
copy a team of 2 members, add 1 to the copyOutputoriginal 3, copy 3Explanation: both teams share one list.copy a team of 2 members, add 1 to the copyOutputoriginal 2, copy 3Explanation: the copy has its own list.the team nameOutputsafe to shareExplanation: String objects cannot change, so copying them is unnecessary.Visual Explanation
- ShallowreferencesoriginalcopylistAsha, Raviboth point to one list shared
- DeeporiginalAsha, RavicopyAsha, Ravinew ArrayList<>(members)
- Add to copycopyAsha, Ravi, Meeraoriginal keeps 2
- Doneindependent
Only mutable inner objects need copying. Immutable ones, such as String, can be shared safely because no one can change them.
Approaches
Both approaches create a deep copy. The first uses a copy constructor; the second overrides clone().
Approach 1: Copy Constructor (Recommended)
Idea: add a constructor that takes another Team and copies its mutable list with new ArrayList<>(other.members).
- Copy immutable fields such as the name directly.
- Create a new list containing the same members.
- Use
new Team(original)wherever a copy is needed.
Time: O(n) · Space: O(n). n is the number of members.
Approach 2: Overridden clone()
Idea: call super.clone() for a field-by-field copy, then replace the shared list with a new one.
- Implement
Cloneable. - Call
super.clone(); this alone is a shallow copy. - Assign a new list to the copy's
membersfield and return it.
Time: O(n) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Copy Constructor (Recommended)
Explicit, type-safe and free of checked exceptions, which is why it is generally preferred.
import java.util.ArrayList;
import java.util.List;
public class CopyConstructorDeep {
static class Team {
String name;
List<String> members;
Team(String name, List<String> members) {
this.name = name;
this.members = members;
}
// Deep copy: a new list with the same elements, so the copies no longer share it
Team(Team other) {
this.name = other.name; // String is immutable, so sharing it is safe
this.members = new ArrayList<>(other.members);
}
Team shallowCopy() {
return new Team(name, members); // shares the same list object
}
}
public static void main(String[] args) {
Team original = new Team("Backend", new ArrayList<>(List.of("Asha", "Ravi")));
Team shallow = original.shallowCopy();
shallow.members.add("Meera");
System.out.println("shallow copy: original " + original.members.size() + ", copy " + shallow.members.size());
original.members.remove("Meera"); // reset
Team deep = new Team(original);
deep.members.add("Meera");
System.out.println("deep copy: original " + original.members.size() + ", copy " + deep.members.size());
}
}
shallow copy: original 3, copy 3 deep copy: original 2, copy 3
Time complexity: O(n) · Space complexity: O(n).
Approach 2: Overridden clone()
Works, but Cloneable has awkward rules: a marker interface, a protected method and a checked exception.
import java.util.ArrayList;
import java.util.List;
public class CloneDeep {
static class Team implements Cloneable {
String name;
ArrayList<String> members;
Team(String name, List<String> members) {
this.name = name;
this.members = new ArrayList<>(members);
}
Team shallowCopy() {
try {
return (Team) super.clone(); // Object.clone() copies fields: the list is shared
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
@Override
public Team clone() {
Team copy = shallowCopy();
copy.members = new ArrayList<>(members); // replace the shared list with a copy
return copy;
}
}
public static void main(String[] args) {
Team original = new Team("Backend", List.of("Asha", "Ravi"));
Team shallow = original.shallowCopy();
shallow.members.add("Meera");
System.out.println("shallow copy: original " + original.members.size() + ", copy " + shallow.members.size());
original.members.remove("Meera");
Team deep = original.clone();
deep.members.add("Meera");
System.out.println("deep copy: original " + original.members.size() + ", copy " + deep.members.size());
}
}
shallow copy: original 3, copy 3 deep copy: original 2, copy 3
Time complexity: O(n) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Copy Constructor | O(n) | O(n) |
| Overridden clone() | O(n) | O(n) |
Here n is the number of members. A deep copy copies every reference in the list once; the member strings themselves are shared because they are immutable.
Interview Tips and Recommended Approach
- Define both terms. Shallow copies the fields; deep copies the objects the fields point to.
- Copy only what can change. Immutable objects never need a deep copy.
- Prefer copy constructors or factory methods to
clone(). - Go as deep as needed. A list of mutable objects needs each element copied too.
Recommended Approach: Copy Constructor
Why: it is explicit, needs no special interface and makes the copied fields visible in one place.