.NET Collection Types: Beyond Array
The Array class is the simplest of the collection types provided with the .NET Framework. But the Framework provides a number of more powerful collection classes. The remaining pages of this chapter describe some of these very useful collection classes: ArrayList, Collection, Queue, and Stack.
Array Lists
Imagine that your program asks the user for input or gathers input from a web site. As it finds objects (strings, books, values, etc.), you would like to add them to an array, but you have no idea how many objects you’ll collect in any given session.
It is difficult to use an array for such a purpose because you must declare the size of an Array object at compile time. If you try to add more objects than you’ve allocated memory for, the Array class will throw an exception. If you do not know in advance how many objects your array will be required to hold, you run the risk of declaring either too small an array (and running out of room) or too large an array (and wasting memory).
The .NET Framework provides a class designed for just this situation. The ArrayList class is an array whose size is dynamically increased as required. The ArrayList class provides many useful methods and properties. A few of the most important are shown in Table 9-4.
Table 9-4. ArrayList members
Method or property |
Purpose |
---|---|
Add( ) |
Method to add an object to the ArrayList |
Capacity |
Property containing the number of elements the array can currently hold |
Clear( ... |
Get Programming Visual Basic .NET, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.