Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What have you used Object.clone() for?

Tags:

java

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?

like image 479
alex Avatar asked Nov 06 '08 21:11

alex


People also ask

What is clone () in Java?

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()

What is clone () concept explain with example?

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.

What is clone and where did you use in 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.

What is the purpose of the following code 1 protected Object clone () throws Clonenot Supportedexception?

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.


1 Answers

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.

like image 193
Julien Chastang Avatar answered Oct 15 '22 13:10

Julien Chastang