【问题标题】:How to make a deep copy of Java ArrayList [duplicate]如何制作Java ArrayList的深层副本[重复]
【发布时间】:2011-10-25 21:52:16
【问题描述】:

可能重复:
How to clone ArrayList and also clone its contents?

试图复制一个 ArrayList。底层对象很简单,包含字符串、整数、BigDecimals、日期和 DateTime 对象。 如何确保对新 ArrayList 所做的修改不会反映在旧 ArrayList 中?

Person morts = new Person("whateva");

List<Person> oldList = new ArrayList<Person>();
oldList.add(morts);
oldList.get(0).setName("Mortimer");

List<Person> newList = new ArrayList<Person>();
newList.addAll(oldList);

newList.get(0).setName("Rupert");

System.out.println("oldName : " + oldList.get(0).getName());
System.out.println("newName : " + newList.get(0).getName());

干杯, P

【问题讨论】:

  • Java 是通过引用传递的。因此,最初您在两个列表中都有“相同”的对象引用......您需要使用 clone() 方法。 AFAIK 你必须分别在每个项目上调用它

标签: java arraylist deep-copy


【解决方案1】:

在添加对象之前克隆对象。例如,而不是newList.addAll(oldList);

for(Person p : oldList) {
    newList.add(p.clone());
}

假设clonePerson 中被正确覆盖。

【讨论】:

  • 是的,clone是浅拷贝,在clone()之后,Person对象中的成员仍然是同一个引用,所以需要根据需要重写clone方法
  • 不假设覆盖,默认clone() 受到保护。
【解决方案2】:
public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

在你的执行代码中:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

【讨论】:

  • @Wulf String 不是 Java 中的原始数据类型
  • @ataulm 字符串在 Java 中是不可变的。由于您无法更改它们,因此克隆它们毫无意义。
  • “克隆没有意义”不同于“你不能克隆”
猜你喜欢
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 2011-05-03
相关资源
最近更新 更多