克隆对象

发布于 2024-12-02 07:29:39 字数 334 浏览 0 评论 0 原文

为了制作对象的副本并访问其数据,什么更好?为什么?

1.创建一个新对象并使用您想要的数据对其进行初始化 通过构造函数克隆

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

2.按原样克隆对象并将其转换为您认为的类型

 HashSet<String> myClone = (HashSet<String>) data.clone();

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

甜尕妞 2024-12-09 07:29:39

绝对使用复制构造函数 - clone() 确实很糟糕(至少大多数人都同意如此。)参见 此处了解详细信息。

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

誰認得朕 2024-12-09 07:29:39

'这取决于'。并非所有类都有复制构造函数。一些类定义了clone(),而其他类则从Object继承它。

如果您正在考虑如何在自己的类中实现复制语义,许多人建议不要克隆,但其他人建议这样做。第三种选择是使用静态工厂方法来完成这项工作。

如果您尝试复制某个现有类,那么您将受到现有实现的支配。也许它有一个 clone() 可以完成您想要的操作,也可能没有。也许它有一个复制构造函数,也许没有。

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

怼怹恏 2024-12-09 07:29:39

克隆不会复制数据,而是复制引用(浅复制)。因此,如果您想要进行深度“复制”并且使其独立于第一个副本,则必须进行“逐项克隆”,通常称为 深层复制(有多种方法可以完成此操作)。

另外,您还可以查看实现该 HashSet 的类的 clone() 方法。如果该类重写了该方法,那么它可能会执行深层复制。我向您推荐这本书:http://www.horstmann.com/corejava.html

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文