vb.net中應用 ArrayList 實例
ArrayList 就是數組列表,它位于 System.Collections名稱空間下。是集和類型。 與 ArrayList 同胞的還有一個List,他們的實用很相似。我們只介紹一些關于ArrayList的一些東東。 ArrayList有三個構造器: ArrayList() ArrayList(int32) ArrayList(ICollection)
ArrayList 就是數組列表,它位于 System.Collections名稱空間下。是集和類型。 與 ArrayList 同胞的還有一個List,他們的實用很相似。我們只介紹一些關于ArrayList的一些東東。
ArrayList有三個構造器:
ArrayList()
ArrayList(int32)
ArrayList(ICollection)
一個簡單的例子如下:
Dim t As New ArrayList()
t.Add("Northsnow")
Dim d As New Collection
d.Add("塞北的雪")
d.Add("http://blog.csdn.net/precipitant")
t.AddRange(d)
For Each aa As String In t
MsgBox(aa.ToString())
Next
'會依次輸出:
'Northsnow
'塞北的雪
'http://blog.csdn.net/precipitant
ArrayList的構造器可以接受一個集和,例子如下:
Dim d As New Collection
d.add("Northsnow")
d.Add("塞北的雪")
d.Add("http://blog.csdn.net/precipitant")
Dim t As New ArrayList(d)
Dim sb As New System.Text.StringBuilder()
If t.Count > 0 Then
sb.Append("ArrayList中共有 成員 ")
sb.Append(t.Count.ToString)
sb.Append(" 個")
For Each aa As String In t
sb.AppendLine()
sb.Append(aa)
Next
End If
MsgBox(sb.ToString)
'最后輸出結果為:
'ArrayList中共有 成員 3 個
'Northsnow
'塞北的雪
'http://blog.csdn.net/precipitant
另外還可以給 ArrayList的構造器傳遞一個整數,以設定ArrayList的初始容量。并可以通過 更改 Capacity屬性的值更改 當前 ArrayList的容量,也可以用 TrimToSize方法將容量壓縮成實際的元素數量,例子如下:
Dim t As New ArrayList(10)
Dim d As New Collection
d.Add("Northsnow")
d.Add("塞北的雪")
d.Add("http://blog.csdn.net/precipitant")
t.AddRange(d)
MsgBox(t.Capacity)
t.Capacity = 6
MsgBox(t.Capacity)
t.TrimToSize()
't.Capacity = t.Count 與 t.TrimToSize() 等效
MsgBox(t.Capacity)
'依次輸出:
'10
'6
'3
由于ArrayList是集和類型,所以它具有一些集和的操作方法。比如 遍歷,查找,插入 等操作。同時 ArrayList還相當于一個大小可自由改變的一維數組。所以當然也可以像對待數組一樣對他進行操作。
原文轉自:http://www.anti-gravitydesign.com