当List重新调整大小因为没有多余的容量时,会添加多少容量?只有1?或者它是否增加容量(使总容量加倍)?
答案 0 :(得分:8)
容量将加倍。
这由以下来源控制:
// Ensures that the capacity of this list is at least the given minimum
// value. If the currect capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min) {
if (_items.Length < min) {
int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
_defaultCapacity
是const int
等于4
。
答案 1 :(得分:4)
这是反射器看到的EnsureCpacity方法。大小将翻倍:)
private void EnsureCapacity(int min)
{
if (this._items.Length < min)
{
int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
if (num < min)
{
num = min;
}
this.Capacity = num;
}
}
答案 2 :(得分:2)
基于以下代码,它看起来是双倍的:
int initialCapacity = 100;
List<string> list = new List<string>(initialCapacity);
Console.WriteLine(list.Capacity);
for(int i = 0; i < list.Capacity; i++){
list.Add("string " + i);
}
list.Add("another string");
Console.WriteLine(list.Capacity); // shows 200, changes based on initialCapacity
答案 3 :(得分:0)
通常加倍。