James Raitsev
James Raitsev

Reputation: 96381

Cloning objects

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

Upvotes: 6

Views: 457

Answers (3)

bmargulies
bmargulies

Reputation: 100003

'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.

Upvotes: 1

santiagobasulto
santiagobasulto

Reputation: 11686

Clone doesn't copy the data, it copy the references(Shallow copy). So, if you want to do a deep "copy" and that it became independent from the first one, you'll have to do a "item by item clonning", commonly refered as deep copy (there are several methods to acomplish this).

Also, you might take a look at the clone() method of the class that implements that HashSet. If that class has overriden that method, then it might perform a deep copy. I recommend you this book: http://www.horstmann.com/corejava.html

Upvotes: 0

Michael Berry
Michael Berry

Reputation: 72254

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

Upvotes: 2

Related Questions