<分区>
java documentation对于 class ArrayList<E>
指定:
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.
这怎么可能?
方法void add(int index, E element)
在此列表中的指定位置插入指定元素,将所有后续元素向右移动。虽然在 ArrayList
的末尾插入 n 元素似乎可以实现 摊销常数时间通过使用几何增长重新分配支持数组,这将不允许在数组中间插入元素时摊销常数时间。
文档是否仅涉及 add(element E)
方法还是有一个巧妙的技巧可以在所有情况下实现摊销常数时间?