A colleague recently asked me how to deep-clone a Map and I realized that I probably have never used the clone() method- which worries me.
What are the most common scenarios you have found where you need to clone an object?
The Java Object clone() method creates a shallow copy of the object. Here, the shallow copy means it creates a new object and copies all the fields and methods associated with the object. The syntax of the clone() method is: object.clone()
Creating a copy using the clone() method The class whose object's copy is to be made must have a public clone method in it or in one of its parent class. Every class that implements clone() should call super. clone() to obtain the cloned object reference. The class must also implement java.
clone() method in Java Object class has a clone method which can be used to copy the values of an object without any side-effect. Assignment operator has a side-effect that when a reference is assigned to another reference then a new object is not created and both the reference point to the same object.
Class CloneNotSupportedException Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.
I assume you are referring to Object.clone()
in Java. If yes, be advised that Object.clone()
has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone()
on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With