ArrayList表示一個可以單獨索引的對象的有序集合。它基本上是一個數組的替代品。 但是,與數組不同,可以使用索引在指定位置添加和刪除列表中的專案,並且數組自動調整大小。 它還允許動態記憶體分配,添加,搜索和排序列表中的專案。
ArrayList類的屬性和方法
下表列出了ArrayList類的一些常用屬性:
| 編號 | 屬性 | 描述 |
|---|---|---|
| 1 | Capacity |
獲取或設置ArrayList可以包含的元素的數量。 |
| 2 | Count |
獲取ArrayList中實際包含的元素的數量。 |
| 3 | IsFixedSize |
獲取一個值,該值指示ArrayList是否具有固定的大小。 |
| 4 | IsReadOnly |
獲取一個值,該值指示ArrayList是否是只讀的。 |
| 5 | Item |
獲取或設置指定索引處的元素。 |
下表列出了ArrayList類的一些常用方法:
| 編號 | 方法 | 描述 |
|---|---|---|
| 1 | Public Overridable Function Add (value As Object) As Integer |
將一個對象添加到ArrayList的末尾。 |
| 2 | Public Overridable Sub AddRange (c As ICollection) |
將ICollection的元素添加到ArrayList的末尾。 |
| 3 | Public Overridable Sub Clear |
刪除ArrayList中的所有元素。 |
| 4 | Public Overridable Function Contains (item As Object) As Boolean |
確定元素是否在ArrayList中 |
| 5 | Public Overridable Function GetRange (index As Integer, count As Integer ) As ArrayList |
返回一個ArrayList,它表示源ArrayList中元素的一個子集。 |
| 6 | Public Overridable Function IndexOf (value As Object) As Integer |
返回ArrayList中或其一部分中第一次出現值的從零開始的索引。 |
| 7 | Public Overridable Sub Insert (index As Integer, value As Object) |
將元素插入指定索引處的ArrayList中。 |
| 8 | Public Overridable Sub InsertRange (index As Integer, c As ICollection) |
將集合的元素插入到指定索引處的ArrayList中。 |
| 9 | Public Overridable Sub Remove (obj As Object ) |
從ArrayList中刪除第一次出現的指定對象。 |
| 10 | Public Overridable Sub RemoveAt (index As Integer) |
刪除ArrayList的指定索引處的元素。 |
| 11 | Public Overridable Sub RemoveRange (index As Integer, count As Integer) |
從ArrayList中刪除一系列元素。 |
| 12 | Public Overridable Sub Reverse |
轉置ArrayList中元素的順序。 |
| 13 | Public Overridable Sub SetRange (index As Integer, c As ICollection ) |
在ArrayList的一系列元素上複製一個集合的元素。 |
| 14 | Public Overridable Sub Sort |
對ArrayList中的元素進行排序。 |
| 15 | Public Overridable Sub TrimToSize |
將容量設置為ArrayList中元素的實際數量。 |
實例
以下示例演示了這個概念:
Imports System.Collections
Module modarraylist
Sub Main()
' Dim al As New ArrayList()
Dim al As ArrayList = New ArrayList()
Dim i As Integer
Console.WriteLine("Adding some numbers:")
al.Add(45)
al.Add(78)
al.Add(33)
al.Add(56)
al.Add(12)
al.Add(23)
al.Add(9)
Console.WriteLine("Capacity: {0} ", al.Capacity)
Console.WriteLine("Count: {0}", al.Count)
Console.Write("Content: ")
For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.Write("Sorted Content: ")
al.Sort()
For Each i In al
Console.Write("{0} ", i)
Next i
Console.WriteLine()
Console.ReadKey()
End Sub
End Module
執行上面示例代碼,得到以下結果 -
F:\worksp\vb.net\collection>vbc modarraylist.vb
F:\worksp\vb.net\collection>modarraylist.exe
Adding some numbers:
Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Sorted Content: 9 12 23 33 45 56 78
