The ArrayList collection allows you to maintain multiple elements, similar to an array; however, the ArrayList collection allows the insertion of elements anywhere in the collection, as well as the removal of any element. In other words, it’s a dynamic structure that can also grow automatically as you add/remove elements. Like an array, the ArrayList’s elements can be sorted and searched. In effect, the ArrayList is a more “convenient” array, a dynamic array. You can also remove elements by value, not only by index. If you have an ArrayList populated with names, you remove the item Charles by passing the string itself as an argument. Notice that Charles is not an index value; it’s the element you want to remove.
Creating an ArrayList
To use an ArrayList in your code, you must first create an instance of the ArrayList class by using the New keyword, as in the following
Dim aList As New ArrayList
The aList variable represents an ArrayList that can hold only 16 elements (the default size). You can set the initial capacity of the ArrayList by setting its Capacity property, which is the number of elements the ArrayList can hold. The ArrayList’s capacity can be increased or reduced at any time, just by setting the Capacity property. You can also specify the collection’s initial capacity in the ArrayList’s constructor:
Dim aList As New ArrayList(1000)
Notice that you don’t have to prepare the collection to accept a specific number of items. Every time you exceed the collection’s capacity, it’s doubled automatically. However, it’s not decreased automatically when you remove items.
The exact number of items currently in the ArrayList is given by the Count property, which is always less than (or, at most, equal to) the Capacity property. (Both properties are expressed in terms of items.) If you decide that you will no longer add more items to the collection, you can call the TrimToSize method, which will set the collection’s capacity to the number of items in the list.