ArrayList()构造函数用于初始化ArrayList类的新实例,该实例将为空,并将具有默认的初始容量。 ArrayList表示可以单独索引的对象的有序集合。基本上,它是数组的替代方法。它还允许动态分配内存,添加,搜索和排序列表中的项目。
句法:
public ArrayList ();
重要事项:
- ArrayList可以容纳的元素数称为ArrayList的容量。如果将元素添加到ArrayList中,则将通过重新分配内部数组来自动增加容量。
- 如果可以估计集合的大小,则指定初始容量将消除在将元素添加到ArrayList时执行大量调整大小操作的需求。
- 此构造函数是O(1)操作。
范例1:
// C# Program to illustrate how
// to create a ArrayList
using System;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// arrlist is the ArrayList object
// ArrayList() is the constructor
// used to initializes a new
// instance of the ArrayList class
ArrayList arrlist = new ArrayList();
// Count property is used to get the
// number of elements in ArrayList
// It will give 0 as no elements
// are present currently
Console.WriteLine(arrlist.Count);
}
}
输出:
0
范例2:
// C# Program to illustrate how
// to create a ArrayList
using System;
using System.Collections;
class Geeks {
// Main Method
public static void Main(String[] args)
{
// arrlist is the ArrayList object
// ArrayList() is the constructor
// used to initializes a new
// instance of the ArrayList class
ArrayList arrlist = new ArrayList();
Console.Write("Before Add Method: ");
// Count property is used to get the
// number of elements in ArrayList
// It will give 0 as no elements
// are present currently
Console.WriteLine(arrlist.Count);
// Adding the elements
// to the ArrayList
arrlist.Add("This");
arrlist.Add("is");
arrlist.Add("C#");
arrlist.Add("ArrayList");
Console.Write("After Add Method: ");
// Count property is used to get the
// number of elements in arrlist
Console.WriteLine(arrlist.Count);
}
}
输出:
Before Add Method: 0
After Add Method: 4
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.arraylist.-ctor?view=netframework-4.7.2#System_Collections_ArrayList__ctor