Cloning Objects

In order to create a copy of the object and gain access to its data, which is better and why?

1. Create a new object and initialize it with data. clone through constructor

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

2. Clone the object as is and apply it to the type you consider

  HashSet<String> myClone = (HashSet<String>) data.clone(); 
+6
source share
3 answers

Definitely use the copy constructor - clone() really badly broken (at least most people agree with this.) For more details see here ./p>

+2
source

"It depends". Not all classes have copy constructors. Some classes define clone() , while others inherit it from Object .

If you are thinking about how to implement copy semantics in your class, many recommend against cloning, but others recommend it. A third alternative is the static factory method, which does the job.

If you are trying to make a copy of an existing class, you are at the mercy of the existing implementation. Maybe it has clone() , which does what you want, and maybe not. Maybe he has a copy constructor, maybe not.

+1
source

The clone does not copy data, copies links ( Small copy ). So, if you want to make a deep “copy” and make it independent of the first, you have to do “clone elements by elements”, usually called a deep copy (there are several ways to do this).

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

0
source

Source: https://habr.com/ru/post/896239/


All Articles