What is deep copy?
Solution and explanation
What it is
A deep copy creates a new object and also recursively copies every mutable object it refers to, so the copy is fully independent of the original.
1. Copy constructors (preferred)
class Address {
String city;
Address(String city) { this.city = city; }
Address(Address other) { this.city = other.city; } // copy constructor
}
class Employee {
String name;
Address address;
List<String> skills;
Employee(Employee other) {
this.name = other.name; // String is immutable: sharing is safe
this.address = new Address(other.address); // new nested object
this.skills = new ArrayList<>(other.skills); // new list
}
}
Employee e2 = new Employee(e1);
e2.address.city = "Noida"; // e1's address is unchanged
2. Deep clone()
@Override
protected Employee clone() throws CloneNotSupportedException {
Employee copy = (Employee) super.clone();
copy.address = new Address(this.address);
copy.skills = new ArrayList<>(this.skills);
return copy;
}
3. Serialization (simple but slow)
ObjectMapper mapper = new ObjectMapper();
Employee copy = mapper.readValue(mapper.writeValueAsString(e1), Employee.class);
Shallow vs deep
| Shallow copy | Deep copy | |
|---|---|---|
| Top-level object | New | New |
| Nested mutable objects | Shared | Copied |
| Speed and memory | Fast, little memory | Slower, more memory |
| Independence | Changes to nested objects affect both | Fully independent |
Note: immutable objects (String, records with immutable fields, List.of) never need copying. Making classes immutable is often simpler than deep copying.
