I was wondering how efficient addAll() method in Java collections is and looked through the JDK code (Sun/Oracle JDK 1.6.0-27). Here is code for ArrayList.addAll(...):


public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}

So here you can see incomming collection content copied into intermediate array.
And here is code for ArrayList.toArray():


public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}

Pay attention that content of internal array is copied in order to return some value. And that's OK because internal array may contain empty cells in its tail. But what we have if we put it all together - if you make arrayList1.addAll(arrayList2) then content of arrayList2 is copied 2 times.

Well... honestly, I beleived before that standard data manipulation routines should be better optimized.