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
在添加对象之前先对其进行克隆。 例如,代替
1 2 3 | for(Person p : oldList) { newList.add(p.clone()); } |
假定在
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
在执行代码中:
1 2 3 | ArrayList<Person> clone = new ArrayList<Person>(); for(Person p : originalList) clone.add(p.clone()); |