Xxxo
Xxxo

Reputation: 1931

Iterators VS ArrayList.addAll() with clone method in JAVA

My question is based on the assumption that the ArrayList.addAll() method does not make new objects but appends the same objects to the ArrayList.

Thus, in order to addAll objects but also have new objects then a construction must be made.

E.g., lets say that the BooClass class implements the Cloneable interface with deep copy and we have:

ArrayList<BooClass> foo1 = new ArrayList<BooClass>();
for (int i = 0; i < 10; i++) foo1.add(new BooClass());

ArrayList<BooClass> foo2 = new ArrayList<BooClass>();

Then, if someone wants to add all elements of foo1 to foo2 as new objects, he should do something like:

foo2.addAll(foo1.clone());

Because:

foo2.addAll(foo1);

would result in ( ? ) foo1 and foo2 having the same BooClass objects in them.

So, if the above is correct, then my question is which of the two is faster:

Iterator<BooClass> itBoo = foo1.iterator();
while(itBoo.hasNext()) foo2.add(itBoo.next().clone());

or:

foo2.addAll(foo1.clone());

?

Upvotes: 3

Views: 1455

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

The two don't do the same thing.

Iterator<BooClass> itBoo = foo1.iterator();
while(itBoo.hasNext()) foo2.add(itBoo.next().clone());

This clones every BooClass object in foo1, and adds the clone to foo2.

Whereas

foo2.addAll(foo1.clone());

Clones the list foo1, resulting in a new ArrayList containing references to the same BooClass objects ass foo1, and adds all those BooClass objects to foo2. The clone operation is completely useless, BTW, since that will have the same effect as simply doing

foo2.addAll(foo1);

If you want a deep clone, the simplest way is

List<BooClass> foo2 = new ArrayList<>(foo1.size());
for (BooClass boo : foo1) {
    foo2.add(boo.clone());
}

Note that clone() is generally considered a bad idea. You should generally prefer a copy constructor:

List<BooClass> foo2 = new ArrayList<>(foo1.size());
for (BooClass boo : foo1) {
    foo2.add(new BooClass(boo));
}

Upvotes: 6

Related Questions