克隆对象
为了制作对象的副本并访问其数据,什么更好?为什么?
1.创建一个新对象并使用您想要的数据对其进行初始化 通过构造函数克隆
HashSet<String> myClone = new HashSet<String>(data);
2.按原样克隆对象并将其转换为您认为的类型
HashSet<String> myClone = (HashSet<String>) data.clone();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
绝对使用复制构造函数 -
clone()
确实很糟糕(至少大多数人都同意如此。)参见 此处了解详细信息。Definitely use a copy constructor -
clone()
is really quite broken (at least most people agree so.) See here for details.'这取决于'。并非所有类都有复制构造函数。一些类定义了
clone()
,而其他类则从Object
继承它。如果您正在考虑如何在自己的类中实现复制语义,许多人建议不要克隆,但其他人建议这样做。第三种选择是使用静态工厂方法来完成这项工作。
如果您尝试复制某个现有类,那么您将受到现有实现的支配。也许它有一个
clone()
可以完成您想要的操作,也可能没有。也许它有一个复制构造函数,也许没有。'It depends'. Not all classes have copy constructors. Some classes define
clone()
and others inherit it fromObject
.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.克隆不会复制数据,而是复制引用(浅复制)。因此,如果您想要进行深度“复制”并且使其独立于第一个副本,则必须进行“逐项克隆”,通常称为 深层复制(有多种方法可以完成此操作)。
另外,您还可以查看实现该 HashSet 的类的
clone()
方法。如果该类重写了该方法,那么它可能会执行深层复制。我向您推荐这本书:http://www.horstmann.com/corejava.htmlClone 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