栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

arraylist的副本不断修改为原始值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

arraylist的副本不断修改为原始值

您仅将对象引用复制到ArrayList中。您需要复制对象本身。

在Java中,所有对象变量实际上都是引用变量。所以代码:

Myclass myObject = new Myclass();Myclass otherObject = myObject;

创建MyClass对象,并将对该Myclass对象的引用存储在引用变量中

myObject
。然后,它创建一个新的参考变量
otherObject
,并将参考数据(例如,内存地址)从复制
myObject
otherObject
。现在,它们引用内存中的同一对象。此时,线

myObject.myMethod();

具有与以下相同的结果

otherObject.myMethod();

您在ArrayList中得到的是对相同对象的不同引用。您想要的是以下之一:

Myclass otherObject = myObject.clone(); // use the clone function// ORMyclass otherObject = new Myclass(myObject); // use a copy constructor

如果使用

clone()
或副本构造函数将对象放入ArrayList ,则ArrayList将包含对相同副本的引用,而不是对相同副本的引用。

正如其他人指出的那样,仅复制引用的副本称为“浅副本”,而复制所引用的对象的副本称为“深副本”。

编辑:为了使此方法有效,您的解决方案不仅要在 您的
类上实现,而且还必须在您类中包含的所有类上实现。例如,考虑

MyClass
哪个具有类型的字段
OtherClass

class MyClass {  private String foo;  private OtherClass bar;  private int x;  MyClass(String f, OtherClass b, int x) {    foo = f;    bar = b;    this.x = x;  }  MyClass(MyClass o) {    //make sure to call the copy constructor of OtherClass    this(new String(o.foo), new OtherClass(o.bar), o.x);  }  // getters and setters}

请注意,这

OtherClass
还需要一个副本构造函数!而且,如果
OtherClass
引用其他类,那么它们也需要复制构造函数。没有办法解决。

最后,您的列表副本将如下所示:

List<MyClass> myNewList = new ArrayList<>(myExistingList.size());for ( MyClass item : myExistingList) {  // use the copy constructor of MyClass, which uses the copy constructor of OtherClass, etc, etc.  myNewList.add(new MyClass(item))}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637574.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号