Shallow Cloning vs Deep Cloning in Java
The easiest way to remember:
Shallow Copy → copies the object, but shares referenced objects.
Deep Copy → copies the object AND creates copies of referenced objects.
1. Simple Example
Suppose we have a Person containing an Address.
class Address {
String city;
Address(String city) {
this.city = city;
}
}
class Person implements Cloneable {
String name;
Address address;
Person(String name, Address address) {
this.name = name;
this.address = address;
}
// Shallow copy
@Override
protected Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
}Shallow Copy
Address address = new Address("Bangalore");
Person p1 = new Person("Ramesh", address);
// Shallow clone
Person p2 = p1.clone();
p2.address.city = "Hyderabad";
System.out.println(p1.address.city);Output:
HyderabadWhy?
p1
|
|---- name = Ramesh
|
↓
Address A
city = Hyderabad
↑
|
|---- p2Both p1 and p2 point to the same Address object.
So:
p1.address == p2.addressis:
true2. Deep Copy
For deep cloning, we create a new Address object as well.
class Person implements Cloneable {
String name;
Address address;
Person(String name, Address address) {
this.name = name;
this.address = address;
}
@Override
protected Person clone() throws CloneNotSupportedException {
Person copy = (Person) super.clone();
// Create a new Address object
copy.address = new Address(this.address.city);
return copy;
}
}Now:
Address address = new Address("Bangalore");
Person p1 = new Person("Ramesh", address);
Person p2 = p1.clone();
p2.address.city = "Hyderabad";
System.out.println(p1.address.city);
System.out.println(p2.address.city);Output:
Bangalore
HyderabadBecause:
p1 p2
| |
↓ ↓
Address A Address B
Bangalore HyderabadThey have different Address objects.
p1.address == p2.addressreturns:
falseInterview Shortcut ⭐
| Shallow Clone | Deep Clone |
|---|---|
| New outer object | New outer object |
| Referenced objects are shared | Referenced objects are also copied |
| Faster | More expensive |
| Changes to nested object affect both | Changes are independent |
super.clone() typically gives shallow copy | Need to explicitly clone/copy nested objects |
One-line interview answer
Shallow cloning creates a new object but copies references as-is, whereas deep cloning creates a new object and recursively creates independent copies of referenced mutable objects.
Easy memory trick
Shallow = New Box + Same Objects
Deep = New Box + New ObjectsImportant: Object.clone() by itself performs a shallow copy. Deep cloning is something you must implement explicitly (or use another copying strategy).
No comments:
Post a Comment