gpt4 book ai didi

java列表无法添加类然后更改原始类而不更改列表中的副本

转载 作者:行者123 更新时间:2023-11-30 04:48:04 34 4
gpt4 key购买 nike

所以我主要用C++编程,而java与c++非常相似。我已经创建了一个这样的列表命令

 List<Item> stuff =new ArrayList<Item>();

其中 Item 是一个基本上存储数据的自定义类。我从文本文件中获取信息并将其存储到 Item.然后我使用 stuff.add 来获取项目类。之后,我使用命令删除项目类中的所有数据,并看到它也删除了列表中的所有数据。基本上我想知道是否有办法添加类的副本而不是类本身的地址。

编辑:所以我发现重新初始化项目类也解决了我的问题,谢谢。

最佳答案

您想要在将项目添加到列表之前克隆该项目。该列表仅包含对您创建的原始项目的引用。因此,当您改变项目时,列表中的项目也会受到影响(它是同一个对象)。

如果您想“断开”放入列表中的项目,那么您可以clone首先。您的项目类需要实现 Cloneable并覆盖 clone()方法。如果 Item 中只有基元,那么您可以简单地执行以下操作:

public Object clone()
{
return super.clone();
}

如果 Item 中有其他对象,那么默认的克隆操作将仅进行浅复制,并且您需要使您的克隆方法更加广泛,以便它进行深复制。来自 Object.clone() 的 Javadoc:

By convention, the object returned by this method should be independent of this object (which is being cloned). To achieve this independence, it may be necessary to modify one or more fields of the object returned by super.clone before returning it. Typically, this means copying any mutable objects that comprise the internal "deep structure" of the object being cloned and replacing the references to these objects with references to the copies. If a class contains only primitive fields or references to immutable objects, then it is usually the case that no fields in the object returned by super.clone need to be modified.

关于java列表无法添加类然后更改原始类而不更改列表中的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10491153/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com