开发者

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(开发者_开发百科);


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜