Java : Shallow Cloning Vs Deep Cloning


Pre-requisite : 

Below are  the list of differences between shallow cloning and deep cloning in java.

Example of Shallow Cloning and Deep Cloning
Java : Shallow Cloning and Deep Cloning

Shallow Cloning

  • Cloned Object and original object are not 100% disjoint.
  • Any changes made to cloned object will be reflected in original object or vice versa.
  • Default version of clone method creates the shallow copy of an object.
  • Shallow copy is preferred if an object has only primitive fields.
  • Shallow copy is fast and also less expensive.

Example: Shallow Cloning Example

Deep Cloning

  • Cloned Object and original object are 100% disjoint.
  • Any changes made to cloned object will not be reflected in original object or vice versa.
  • To create the deep copy of an object, you have to override clone method.
  • Deep copy is preferred if an object has references to other objects as fields.
  • Deep copy is slow and very expensive.

Example: Deep Cloning Example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s