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:

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

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

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) {

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

Leave a Comment