Java Copy Constructor ArrayLists

Note: Cloning the lists, isn’t the same as cloning the elements in the list.

None of these approaches work the way you want them to:

//1
people = new ArrayList<Cool>(other.people);

//2
people = new ArrayList<Cool>();
for(Cool p : other.people) {
    people.add(p);
}

The approaches above will fill people such that it contains the same elements as other.people.

However, you don’t want it to contain the same elements. You want to fill it with clones of the elements in other.people.

The best approach would be something like this:

people = new ArrayList<Cool>(other.people.size());
for(Cool p : other.people) {
    people.add((Cool)p.clone());
}

Make sure Cool implements Cloneable. Override clone() if necessary.

Leave a Comment