Deep copy vs Shallow copy - Java

Shallow:
Before Copy Shallow Copying Shallow Done
Deep:
Before Copy Deep Copying Deep Done


------------------------------------------------------------------------------------------

1) The clone() method is used to create a copy of an object in Java. In order to use clone() method, class must implement java.lang.Cloneable interface and override protected clone() method from java.lang.Object.

A call to clone() method will result in CloneNotSupportedException if that class doesn't implement Cloneable interface.


2) No constructor is called during cloning of Object in Java.


3) Default implementation of clone() method in Java provides "shallow copy" of object, because it creates copy of Object by creating new instance and then copying content by assignment, which means if your class contains a mutable field, then both original object and clone will refer to same internal object. This can be dangerous because any change made on that mutable field will reflect in both original and copy object. In order to avoid this, override clone() method to provide the deep copy of an object.


4) By convention, clone of an instance should be obtained by calling super.clone() method, this will help to preserve invariant of object created by clone() method i.e. clone != original and clone.getClass() == original.getClass(). Though these are not absolute requirement as mentioned in Javadoc.


5) A shallow copy of an instance is fine, until it only contains primitives and Immutable objects, otherwise, you need to modify one or more mutable fields of object returned by super.clone(), before returning it to caller.


Read more: http://javarevisited.blogspot.com/2013/09/how-clone-method-works-in-java.html#ixzz3ntQh3cVK


----------------------------------------------------------------------------------------------
Java Deep-Cloning library The cloning library is a small, open source (apache licence) java library which deep-clones objects. The objects don't have to implement the Cloneable interface. Effectivelly, this library can clone ANY java objects. It can be used i.e. in cache implementations if you don't want the cached object to be modified or whenever you want to create a deep copy of objects.
Cloner cloner=new Cloner();
XX clone = cloner.deepClone(someObjectOfTypeXX);

Comments

Popular posts from this blog

EJB - Stateful vs Stateless

Mirror binay tree - Java