Deep/Shallow Cloning in Java


Cloning an object is a popular way to create copies of the Java object. Default Cloning type in Java is “Shallow Cloning”. Object Cloning can be of two types namely :

  • Shallow Cloning
  • Deep Cloning

Shallow copy is the copy of all the mutable fields of the original object so if the original object graph contains an object then the reference is copied, Hence if the contained object is changed the change is reflected in shallow copy object as well.

Deep Cloning is the recursive copy of all mutable fields(objects) from its object graph , hence the change in the original copy does not affect the deep cloned object. Deep copy object is 100% disjoint from original object.

Moreover if your object contains only immutable/primitive fields then deep copy or shallow copy both have same behaviour.

Multiple Ways of Deep Cloning :

  • Implementing Cloneable Interface and manually write implementation of clone() method. Though this approach is preferred but sometimes it becomes a cumbersome due to large number of fields in the object.
  • Using the ObjectInput/OutputStream classes to serialize the object and deserialize to create a deep copy. Sample Code is below:
public DummyObject clone() 
{
DummyObject clonedMessage = null;
ByteArrayOutputStream baos = null;
ByteArrayInputStream bais = null;
try
{
baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
clonedMessage = (DummyObject) ois.readObject();
}
catch (Exception e)
{
logger.error("Unable to clone DummyObject: ", e);
}
finally
{
try
{
if(baos != null)
baos.close();
}
catch (IOException e)
{}
try
{
if(bais != null)
baos.close();
}
catch (IOException e)
{}
}
return clonedMessage == null ? new DummyObject() : clonedMessage;
}
  • Using open source Serialization/Deserialization libraries like Gson/Jackson/Apache Commons Lang classes. Below you can find sample examples.

Please Note : All the Serialization/Deserialization approaches come with a performance hit due to the expensive overhead of serialization/deserialization.



What am I missing here ? Let me know in comments section and I'll add in!

What’s next? Subscribe Learn INQuiZitively to be the first to read my stories.