ArrayList(Int32)构造函数用于初始化ArrayList类的新实例,该实例将为空并具有指定的初始容量。 ArrayList表示可以单独索引的对象的有序集合。基本上,它是数组的替代方法。它还允许动态分配内存,添加,搜索和排序列表中的项目。
Syntax: public ArrayList (int capacity);
Here, capacity is the number of elements that the new list can initially store.
Exception: This will give ArgumentOutOfRangeException if the capacity is less than zero.
重要事项:
- ArrayList可以容纳的元素数称为ArrayList的容量。如果将元素添加到ArrayList中,则将通过重新分配内部数组来自动增加容量。
- 如果可以估计集合的大小,则指定初始容量将消除在将元素添加到ArrayList时执行大量调整大小操作的需求。
- 此构造函数是O(n)运算,其中n是容量。
下面的程序说明了上面讨论的构造函数的用法:
范例1:
// C# Program to illustrate how
// to create a ArrayList having
// specified initial capacity
using System;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// arrlist is the ArrayList object
// ArrayList(10) is the constructor
// used to initializes a new
// instance of the ArrayList class
// having 10 as capacity
ArrayList arrlist = new ArrayList(10);
Console.Write("Number of elements: ");
// Count property is used to get the
// number of elements in ArrayList
// It will give 0 as no elements
// are present
Console.WriteLine(arrlist.Count);
Console.Write("Capacity of ArrayList: ");
// using capacity property
Console.WriteLine(arrlist.Capacity);
// inserting elements to ArrayList
arrlist.Add("C");
arrlist.Add("C++");
arrlist.Add("Java");
arrlist.Add("C#");
Console.Write("Number of elements: ");
// Count property is used to get the
// number of elements in ArrayList
Console.WriteLine(arrlist.Count);
Console.Write("Capacity of ArrayList: ");
// using capacity property
Console.WriteLine(arrlist.Capacity);
}
}
输出:
Number of elements: 0
Capacity of ArrayList: 10
Number of elements: 4
Capacity of ArrayList: 10
示例2:对于ArgumentOutOfRangeException
// C# Program to illustrate how
// to create a ArrayList having
// specified initial capacity
using System;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// arrlist is the ArrayList object
// taking capacity less than zero
ArrayList arrlist = new ArrayList(-4);
// using capacity property
Console.WriteLine(arrlist.Capacity);
}
}
运行时错误:
Unhandled Exception:
System.ArgumentOutOfRangeException: ‘capacity’ must be non-negative.
Parameter name: capacity
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.arraylist.-ctor?view=netframework-4.7.2#System_Collections_ArrayList__ctor_System_Int32_