4.6. CollectionsVisual Basic defines an associative array object called a collection. Although similar to an array in that elements appear in a specific order, a collection stores its elements as key-value pairs. Once in a collection, each element can be retrieved by position, by key, or by iterating through the collection one element at a time. Five of the Collection class's members are especially useful.
The following code defines a collection of state names, using the state abbreviation as the key. Dim states As New Collection states.Add("New York", "NY") states.Add("Michigan", "MI") The elements of this collection can then be iterated using the For Each...Next construct. Dim oneState As String For Each oneState In states MsgBox(oneState) Next oneState Like arrays, collection members are accessible by their index value. The lower bound of a collection is always one (1). New in 2005. The 2005 release of Visual Basic includes a new generics feature that allows collection (and other class) instances to be tied to a specific data type. See Chapter 10 for details on using this new feature. |