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();
Definitely use a copy constructor - clone()
is really quite broken (at least most people agree so.) See here for details.
'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.
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