Wednesday, March 9, 2011

Deep Copy and Shallow copy

http://javapapers.com/core-java/java-clone-shallow-copy-and-deep-copy/

Generally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy

clone() method in Object is protected.

to overwrite clone(), you must implement Cloneable marker interface or else you will get CloneNotSupportedException.

deep copy the copied object contains some other object its references are copied recursively . be careful with cyclic.
If you don’t want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies.

No comments:

Post a Comment