ArrayList表示可以单独索引的对象的有序集合。基本上,它是数组的替代方法。它还允许动态分配内存,添加,搜索和排序列表中的项目。 ArrayList.Capacity属性用于获取或设置ArrayList可以包含的元素数。
ArrayList类的属性:
- 可以随时在数组列表集合中添加或删除元素。
- 不能保证对ArrayList进行排序。
- ArrayList的容量是ArrayList可以容纳的元素数。
- 可以使用整数索引访问此集合中的元素。此集合中的索引从零开始。
- 它还允许重复的元素。
- 不支持将多维数组用作ArrayList集合中的元素。
句法:
public virtual int Capacity { get; set; }
返回值: ArrayList可以包含的元素数。
例外情况:
- ArgumentOutOfRangeException:如果将Capacity设置为小于Count的值,即ArrayList中的元素数。
- OutOfMemoryException:如果系统上没有足够的可用内存。
例子:
// C# code to get or set the number
// of elements that the ArrayList can contain
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main() {
// Creating an ArrayList
ArrayList myList = new ArrayList();
// Adding elements to ArrayList
myList.Add(1);
myList.Add(2);
myList.Add(3);
myList.Add(4);
myList.Add(5);
// Displaying count of elements of ArrayList
Console.WriteLine("Number of elements: " + myList.Count);
// Displaying Current capacity of ArrayList
Console.WriteLine("Current capacity: " + myList.Capacity);
}
}
输出:
Number of elements: 5
Current capacity: 8
重要事项:
- 容量是ArrayList可以存储的元素数。 Count是ArrayList中实际存在的元素数。
- 容量始终大于或等于Count 。如果在添加元素时计数超过了容量,则通过在复制旧元素和添加新元素之前重新分配内部数组来自动增加容量。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.arraylist.capacity?view=netframework-4.7.2