不同的容器,扩容方法是不一样。比如
arraylist 是 int newCapacity = (oldCapacity * 3)/2 + 1;
hashmap 是 2 * table.length
------------
搜索了一下,至于各种语言各种容器扩容算法是不一样。wiki上,动态数组讲到如何扩容。
Dynamic array
Geometric expansion and amortized cost[edit]
To avoid incurring the cost of resizing many times, dynamic arrays resize by a large amount, such as doubling in size, and use the reserved space for future expansion. The operation of adding an element to the end might work as follows:
function insertEnd(dynarray a, element e)
if (a.size = a.capacity)
// resize a to twice its current capacity:
a.capacity ← a.capacity * 2
// (copy the contents to the new memory location here)
a[a.size] ← e
a.size ← a.size + 1
As n elements are inserted, the capacities form a geometric progression. Expanding the array by any constant proportion ensures that inserting n elements takes O(n) time overall, meaning that each insertion takes amortized constant time. The value of this proportion a leads to a time-space tradeoff: the average time per insertion operation is about a/(a−1), while the number of wasted cells is bounded above by (a−1)n. The choice of a depends on the library or application: some textbooks use a = 2,a = 3/2Python's list data structure uses a = 9/8.
Many dynamic arrays also deallocate some of the underlying storage if its size drops below a certain threshold, such as 30% of the capacity. This threshold must be strictly smaller than 1/a in order to provide hysteresis (provide a stable band to avoiding repeatedly growing and shrinking) and support mixed sequences of insertions and removals with amortized constant cost.
Dynamic arrays are a common example when teaching amortized analysis.https://zh.wikipedia.org/wiki/%E5%B9%B3%E6%91%8A%E5%88%86%E6%9E%90
平摊分析
一个简单的例子,在某个特定实现的动态数组中,我们在每次数组溢出时增长数组的长度至原来的两倍。因此需要数组空间分配,在最坏情况下一个插入操作需要O(n)的时间。但是,一个 n 个插入的操作序列仍然可以在 O(n) 的时间内完成,因为剩下的插入可以在常数时间内完成,因此 n 个插入可以在 O(n) 的时间内完成。因此每操作的平摊耗费为O(n) / n = O(1)。