How to make a deep copy of Java ArrayList [duplicate]

删除回忆录丶 提交于 2019-11-26 05:27:01

问题


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

trying to make a copy of an ArrayList. The underlying object is simple containing on Strings, ints, BigDecimals, Dates and DateTime object. How can I ensure that the modifications made to new ArrayList are not reflected in the old 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());

Cheers, P


回答1:


Cloning the objects before adding them. For example, instead of newList.addAll(oldList);

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

Assuming clone is correctly overriden inPerson.




回答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;
    }
}

In your executing code:

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


来源:https://stackoverflow.com/questions/7042182/how-to-make-a-deep-copy-of-java-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!