The java documentation for class ArrayList<E>
specifies that:
The
size
,isEmpty
,get
,set
,iterator
, andlistIterator
operations run in constant time. Theadd
operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for theLinkedList
implementation.Each
ArrayList
instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to anArrayList
, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
How is this possible?
The method void add(int index, E element)
inserts the specified element at the specified position in this list, shifting all subsequent elements to the right. While it seems possible to achieve amortized constant time to insert n elements at the end of the ArrayList
by reallocating the backing array using geometric growth, this would not allow for amortized constant time when inserting elements in the middle of the array.
Does the documentation only refer to the add(element E)
method or is there a neat trick to achieve amortized constant time in all cases?