Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning objects

Tags:

java

object

clone

For the purposes of making a copy of an object and getting access to its data, what is better and why?

1. Create a new object and initialize it with the data you want to clone through the constructor

 HashSet<String> myClone = new HashSet<String>(data);

2. Clone object as is and cast it to the type you believe it to be

 HashSet<String> myClone = (HashSet<String>) data.clone();
like image 821
James Raitsev Avatar asked Aug 30 '11 19:08

James Raitsev


2 Answers

Definitely use a copy constructor - clone() is really quite broken (at least most people agree so.) See here for details.

like image 103
Michael Berry Avatar answered Oct 11 '22 11:10

Michael Berry


'It depends'. Not all classes have copy constructors. Some classes define clone() and others inherit it from Object.

If you are thinking about how to implement copy semantics in your own class, many people recommend against clone, but others recommend for it. A third alternative is a static factory method that does the work.

If you are trying to make a copy of some existing class, you are at the mercy of the existing implementation. Maybe it has a clone() that does what you want, and maybe it doesn't. Maybe it has a copy constructor, maybe it doesn't.

like image 23
bmargulies Avatar answered Oct 11 '22 13:10

bmargulies