(Let's build on SE Platform 6)
It all depends on actual collection implementation. In your example we have
Collection<Integer> col = new ArrayList<Integer>();
and addAll method in ArrayList is overriden. No iterations whatsoever.
Here's the source:
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;
}
As you might notice c.toArray() also depends on actual implementation. Again, in your case Arrays.asList() results in ArrayList which one's version of toArray() method looks like this:
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
This static method is based on System.arraycopy
So actually what we deal here with is two calls of System.arraycopy which is not that bad actually because it's a native method, specifically optimized for current operation system.
So, to sum it all up in Mr. polygenelubricants' style:
- varags + autoboxing creates
Integer[]
Arrays.asList creates an ArrayList<Integer>
ArrayList.addAll calls System.arraycopy(size)x2, size = 5
In your case of 5 objects in the array Collections.addAll is of cource faster. BUT irrelevant with such a small array size. On the other hand if it was, say, 100k elements in an array then col.addAll(Arrays.asList(...)) is much more efficient 'cause with native method it is a single memcpy/memmove we dealing with as opposed to 100k iterations/copy operations.
And again, it all depends on collection's implementation. LinkedList for example will iterate over it as was expected.