如何制作Java ArrayList的深层副本

How to make a deep copy of Java ArrayList

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How to clone ArrayList and also clone its contents?

试图制作一个ArrayList的副本。 基础对象很简单,包含Strings,ints,BigDecimals,Dates和DateTime对象。
如何确保对新ArrayList所做的修改不会反映在旧ArrayList中?

1
2
3
4
5
6
7
8
9
10
11
12
13
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


在添加对象之前先对其进行克隆。 例如,代替newList.addAll(oldList);

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

假定在Person中正确覆盖了clone


1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
    }
}

在执行代码中:

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