c# - C# Arraylist 中的容量属性

标签 c#

我正在研究 C# 中 Arraylist 的属性。我所做的是:

ArrayList listInt = new ArrayList();
listInt.Add(9);
listInt.Add(10);
listInt.Add(11);
Console.WriteLine($"Capacity Before: {listInt.Capacity}");

输出结果为 4,很好。 接下来我尝试了 AddRange() 属性:

ArrayList list2 = new ArrayList();
list2.Add("SAM");
list2.Add("MAN");
list2.Add("TAN");
listInt.AddRange(list2);
Console.WriteLine($"Capacity After: {listInt.Capacity}");

输出为 8。

输出

a

我的ArrayList容量怎么变成8了?

最佳答案

因为你在列表中又添加了 3 个元素...

Capacity是内部数组的大小...它从 0 开始,然后在第一次添加时默认为 4。当它需要更多容量时,它会增加 2 倍。这使内存复制保持在最低限度(以少量内存为代价)。

注意:不要将CapacityCount 混淆不过,它们是不同的东西

你向你的数组添加 3 个元素

ArrayList listInt = new ArrayList(); // capacity = 0 
listInt.Add(9);                      // capacity = 4
listInt.Add(10);                     // capacity = 4
listInt.Add(11);                     // capacity = 4

因此,当您将第一个元素添加到列表时,Add 会在内部调用 EnsureCapacity。看起来像这样 ( Full Source Here )

private const int _defaultCapacity = 4;

...
private void EnsureCapacity(int min)
{
   if (_items.Length < min)
   {
      int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;
      ...
   }
}

注意 _items.Length * 2 ...

listInt.AddRange(list2);             // capacity = 8

你的列表中可能只有 3 个元素,但容量是 4。现在你再添加 3 个元素,它别无选择,只能将容量乘以 2


List.Capacity Property

Gets or sets the total number of elements the internal data structure can hold without resizing.

List.Count Property

Gets the number of elements contained in the List.

关于c# - C# Arraylist 中的容量属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49891234/

相关文章:

c# - 在 SerializationInfo 中获取具有值的成员

c# - ASP.NET Core RC2 和 .NET 4.5.1 应用程序之间的共享 cookie 身份验证

c# - 为什么 XSD 序列显示不明确

c# - 无法从标记为异步的方法返回 IObservable<T>

c# - 缓慢嵌套 'for' 循环读取 Excel 对象

c# - 如何获取某个 GridView 列中的所有值?

c# - C# 的省略号(以一个完整的词结尾)

c# - 使用 Json.NET JsonSchemaGenerator 将 JSON Schema 属性(标题、描述)添加到 C# 类属性

c# - 通过进程名称取消隐藏进程?

c# - 构建要在 C# 中使用的 F# 库