Visual Basic .NET includes a large assortment of pre-built classes that store and manage groups of objects. These collection classes provide a wide variety of different features, so the right class for a particular purpose depends on your application.
For example, an array is good for storing objects in a particular fixed order. An ArrayList enables you to add, remove, and rearrange its objects much more easily than an array does. A Queue lets a program easily add items and remove them in first in, first out order. In contrast, a Stack lets the program remove items in last in, first out order.
This chapter describes these different kinds of collection classes and provides tips for selecting the right one for various purposes.
The word collection means a group of objects that should be kept together. For example, a coin collection is a group of coins that you keep together because they are rare, valuable, or otherwise interesting.
Unfortunately, the idea of a collection is such a useful concept that Visual Basic adopted the word and made a specific class named Collection. The Collection class does keep a group of objects together, but it reserves for its own use the perfect word for these kinds of groups of objects.
That leads to some semantic ambiguity when you talk about collection classes. Do you mean the Collection class? Or do you mean some other class that groups objects? Even the Visual Basic documentation has this problem and sometimes uses collection classes to mean classes that group things together.
This chapter describes the Collection class as well as other collection classes.
One of the most basic Visual Basic entities that groups objects is an array. An array stores data values or references to objects in a simple block of memory with one entry directly following another. The Array class does provide some special methods for manipulating arrays (such as reversing, sorting, or searching the array).
The Collection class provides a few specific features for working with its group of objects. It enables you to add an item to the Collection, optionally specifying a key for the item. You can then search for the item or remove the item using its key or its index in the Collection.
One of the key features of the Collection class is that it supports enumerators and For Each loops. That lets you easily loop over the objects in a Collection without worrying about the number of objects it contains.
Other classes derived from the Collection class provide additional features. For example, the HashTable class can store a large number of objects with associated keys very efficiently. The Queue class makes it easy to work with objects on a first in, first out (FIFO) basis, whereas the Stack class helps you work with objects in a last in, first out order (LIFO).
The remainder of this chapter describes these classes in detail.