ArrayList - What can I do with it?
The purpose of this tutorial is to quicly show how an ArrayList can be used to
manage a list of items using some of the list manipulation methods.
An ArrayList contains a list of items in a linear fashion. As more items are
added to the list, it will expand as nessecary. The items remain in
relative position to other items unless manually modified. This gives a secure
reassurance that the order will be maintained.
Creating an ArrayList is just like creating any other object.
Dim daughters As ArrayList
Set daughters = New ArrayList
This is the default creation of an ArrayList with a default capacity of 16 items.
Once a new ArrayList has been created, items can be added by calling the Add method.
daughters.Add "Jan"
daughters.Add "Cindi"
This adds two string items to the list. The order in which they were added is maintained
within the list. The list is zero-based. This means that the first item is at index 0.
While the Add method appends the new value to the end of the list, sometimes
it is desirable to place items at a specific place within the list. To accomplish
this you can use the Insert method.
daughters.Insert 0, "Marsha"
This inserts the new value at the beginning of the list. The existing items in
the list are pushed out by one position to make room for the newly inserted value.
It seems that the wrong spelling was used for 'Cindy'.
If there is an item that is to be removed, it can be removed by its value using
the Remove method. Unlike the RemoveAt, the Remove method
searches the list for the first occurence of the value being requested to be removed.
daughters.Remove "Cindi"
daughters.Add "Cindy"
Now the list contains all three of the daughters. The number of daughters in
the list can be verified using the Count property.
Debug.Print "Number of Daughters: "; daughters.Count
' output
' Number of Daughters: 3
Now that the number of daughters is known in the list, we want to know their
names aswell. We can iterate over the list using For..Each and retrieve each
name in the list.
Dim name As Variant
For Each name In daughters
Debug.Print "Name: "; name
Next name
' output
' Name: Marsha
' Name: Jan
' Name: Cindy
We have seen the list that we created. We want to see the names in alphabetical
order instead. This can be accomplished within the list by using the Sort method.
daughters.Sort
For Each name in daughters
Debug.Print "Name: "; name
Next name
' output
' Name: Cindy
' Name: Jan
' Name: Marsha
As you can see, with just the few methods shown in this tutorial, many powerful manipulations can
be accomplished with little code. There are many more methods in ArrayList to be
explored and utilized.
I hope this tutorial gives some insight into the power of the ArrayList class.
|