Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 342
Pnutz Avatar asked Aug 12 '11 15:08

Pnutz


People also ask

How do you make a deep copy of a list in Java?

Deep copy of Java class. In Java, to support deep copy, we must override the clone() of model classes. In clone() method, we must ensure that when somebody invokes object. clone() method then it must return a deep copy of that model class (e.g. Employee class).

How do you shallow copy an ArrayList?

ArrayList clone() method is used to create a shallow copy of the list. In the new list, only object references are copied. If we change the object state inside the first ArrayList, then the changed object state will be reflected in the cloned ArrayList as well.

Can we clone ArrayList in Java?

The Java ArrayList clone() method makes the shallow copy of an array list. Here, the shallow copy means it creates copy of arraylist object. To learn more on shallow copy, visit Java Shallow Copy. Here, arraylist is an object of the ArrayList class.


1 Answers

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.

like image 103
Serabe Avatar answered Oct 21 '22 14:10

Serabe