67

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
  • Java is pass by reference. So initially you have the "same" object reference in both the lists...You'll need to use the clone() method. AFAIK you'll have to call it on each item separately Commented Aug 12, 2011 at 15:14

2 Answers 2

37

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.

Sign up to request clarification or add additional context in comments.

2 Comments

yes, clone is shallow copy, after the clone(), the member in the Person object is still the same reference, so you need to override the clone method according to your needs
Without the assumption of overriding, default clone() is protected.
25
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());

3 Comments

@Wulf String isn't a primitive data type in Java
@ataulm String's are immutable in Java. Since you cannot change them, there's no point in cloning them.
"there's no point in cloning" is different from "You can't clone"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.