What is the time complexity of adding an element at the beginning of an ArrayList?

Adding an element to beginning of array is O(n) - it would require to shift all the existing elements by one position.

All elements in an array list are stored in a contiguous array. If you add more elements than the current size of the array - it will be grown automatically to accommodate the new element.

Addition to the end is O(1) amortized over multiple insertions.


ArrayList.add(0, element) takes linear time, but the constant is very low, because it can use the blazing fast System.arraycopy.

Tags:

Java