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

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

This question is related to java arraylist deep-copy

The answer is


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.


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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to deep-copy

Why and when to use angular.copy? (Deep Copy) How to deep copy a list? Copying an array of objects into another array in javascript How create a new deep copy (clone) of a List<T>? How to make a deep copy of Java ArrayList How do I copy a hash in Ruby? How do I clone a range of array elements to a new array? How to clone ArrayList and also clone its contents? What is the difference between a deep copy and a shallow copy?