它表示可以单独编制索引的对象的有序集合。它基本上是一个数组的替代品。 但是,与数组不同,可以使用索引来从列表中指定位置添加和删除项目,并且数组自动调整大小。 它还允许动态内存分配,添加,搜索和排序列表中的项目。
ArrayList类的方法和属性
下表列出了ArrayList
类的一些常用属性:
属性 | 描述 |
---|---|
Capacity | 获取或设置ArrayList 可以包含的元素数。 |
Count | 获取ArrayList 中实际包含的元素数。 |
IsFixedSize | 获取一个值,指示ArrayList 是否具有固定大小。 |
IsReadOnly | 获取一个值,指示ArrayList 是否为只读。 |
Item | 获取或设置指定索引处的元素。 |
下表列出了ArrayList
类的一些常用方法:
序号 | 方法 | 描述 |
---|---|---|
1 | public virtual int Add(object value); |
将对象添加到ArrayList 的末尾。 |
2 | public virtual void AddRange(ICollection c); |
将ICollection 元素添加到ArrayList 的末尾。 |
3 | public virtual void Clear(); |
从ArrayList 中删除所有元素。 |
4 | public virtual bool Contains(object item); |
确定元素是否在ArrayList 中。 |
5 | public virtual ArrayList GetRange(int index, int count); |
返回一个ArrayList ,它表示源ArrayList 中元素的一个子集。 |
6 | public virtual int IndexOf(object); |
返回ArrayList 或其一部分中从零开始第一次出现值的索引。 |
7 | public virtual void Insert(int index, object value); |
在指定索引的ArrayList 中插入一个元素。 |
8 | public virtual void InsertRange(int index, ICollection c); |
将集合的元素插入到指定索引的ArrayList 中。 |
9 | public virtual void Remove(object obj); |
从ArrayList 中删除指定第一次出现的对象。 |
10 | public virtual void RemoveAt(int index); |
删除ArrayList 的指定索引处的元素。 |
11 | public virtual void RemoveRange(int index, int count); |
从ArrayList 中删除一系列元素。 |
12 | public virtual void Reverse(); |
反转ArrayList 中元素的顺序。 |
13 | public virtual void SetRange(int index, ICollection c); |
在ArrayList 中的一系列元素上复制集合的元素。 |
14 | public virtual void Sort(); |
对ArrayList 中的元素进行排序。 |
15 | public virtual void TrimToSize(); |
将容量设置为ArrayList 中实际的元素数量。 |
例子
以下示例演示了上述概念:
using System;
using System.Collections;
namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
Console.WriteLine("Adding some numbers:");
al.Add(41);
al.Add(70);
al.Add(133);
al.Add(56);
al.Add(120);
al.Add(213);
al.Add(90);
al.Add(111);
Console.WriteLine("Capacity: {0} ", al.Capacity);
Console.WriteLine("Count: {0}", al.Count);
Console.Write("Content: ");
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.Write("Sorted Content: ");
al.Sort();
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
Adding some numbers:
Capacity: 8
Count: 8
Content: 41 70 133 56 120 213 90 111
Sorted Content: 41 56 70 90 111 120 133 213