ArrayList internally uses array object to add(or store) the elements. In other words, ArrayList is backed by Array data -structure.The array of ArrayList is resizable (or dynamic).
Array is faster than ArrayList because ArrayList internally uses an array. if we can directly add elements in Array and indirectly add an element in Array through ArrayList always directly mechanism is faster than an indirect mechanism.
There is two overloaded add() methods in ArrayList class:
add(Object)
: adds an object to the end of the list.add(int index, Object )
: inserts the specified object at the specified position in the list.How the size of ArrayList grows dynamically?
public boolean add(E e)
{
ensureCapacity(size+1);
elementData[size++] = e;
return true;
}
An important point to note from the above code is that we are checking the capacity of the ArrayList, before adding the element. ensureCapacity() determines what is the current size of occupied elements and what is the maximum size of the array. If the size of the filled elements (including the new element to be added to the ArrayList class) is greater than the maximum size of the array then increase the size of the array. But the size of the array can not be increased dynamically. So what happens internally is new Array is created with the capacity
Till Java 6
int newCapacity = (oldCapacity * 3)/2 + 1;
(Update) From Java 7
int newCapacity = oldCapacity + (oldCapacity >> 1);
also, data from the old array is copied into the new array.
Having overhead methods in ArrayList that's why Array is faster than ArrayList
.