Collections: Arrays are convenient for storing
related data, but accessing individual elements can be a problem. Arrays should
be accessed by their contents. Visual
Basic provides an alternative: collections. Similar to an array, a collection
stores related items, in this case, objects that have properties and methods.
The advantage of a collection over an array is that the collection lets you
access its items via a key.
To use a collection, you must first
declare a collection variable, as follows:
Dim
Temperatures As New Collection
The keyword New tells Visual
Basic to create a new collection and name it Temperatures.
The collection object provides three
methods and one property:
• Add method Adds
items to the collection
• Remove method
Deletes an item from the collection by index or key
• Item method
Returns an item by index or by key
• Count property
Returns the number of items in the collection
Adding to a Collection: The Add method adds new items to the collection and it has the following syntax: collection. Add value, key, before, after
To add a new
element to a collection, assign its value to the item argument and its
key to the key argument. To place the new item in a specific location in
the array, specify one of the arguments before or after (but not
both).
Ex. Temperatures.Add 78, “San Francisco”
Removing an Item from a Collection: The Remove method removes an item from
a collection. The index argument can be either the position of the item
you want to delete or the item’s key. To remove the city of Atlanta from your
collection of temperatures, use the following statement:
Ex. Temperatures.Remove “Atlanta”
Or, if you know
the city’s order in the collection, specify the index in place of the key:
Ex. Temperatures.Remove 6
Returning Items in a Collection: The Item method returns the value of
an item in the collection. As with the Remove method, the index can be either
the item’s position in the collection or its key. To recall the temperature in
Atlanta, use one of the following statements:
Ex. T1 = Temperatures.Item(“Atlanta”)
T1 = Temperatures.Item(3)
Counting a Collection: The Count property returns the number of items in the collection. To find out how many cities have been entered so far in the Temperatures collection, use the following statement:
Ex. Temperatures.Count