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
评论前必须登录!
注册