如何制作Java ArrayList的深层副本

时间:2011-08-12 15:12:10

标签: java arraylist deep-copy

  

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

尝试制作ArrayList的副本。底层对象很简单,包含字符串,整数,BigDecimals,Dates和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

2 个答案:

答案 0 :(得分:32)

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

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

假设clone中正确覆盖Person

答案 1 :(得分:19)

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