An ArrayList enables you to store lists of objects (any type of object, even other ArrayLists). Using an ArrayList is similar to using an array, except that an ArrayList does not have any fixed upper bound. An ArrayList also has a number of useful properties and functions that it does not share with an array.

You can create a new ArrayList by using the following statement:

colArrayList = New ArrayList()

This statement creates an ArrayList that can initially store 16 objects. If you attempt to store more than 16 objects, the capacity of the ArrayList is automatically doubled. The capacity keeps doubling to handle the number of elements added.

If you know the number of elements that an ArrayList will store before you create the ArrayList, you can get the (ever so slight) performance benefit by declaring the ArrayList with a particular starting capacity. For example, if you know that an ArrayList will be used to store 100 items, you can declare it like this:

colArrayList = New ArrayList( 100 )

This ArrayList is declared to handle 100 elements. If you add a 101st element, the capacity of the ArrayList automatically doubles to 200.

You can determine the number of elements in an ArrayList at any time by using the Count property. You can determine the current capacity of an ArrayList at any time by using the Capacity property. For example, the following statements display the numbers 0 and 16:

The numbers 0 and 16 are displayed because they are the initial values of the Count and Capacity properties.

If you are working with a really huge ArrayList, you can trim its capacity back to its current size by using the TrimToSize method as follows:

colArrayList.TrimToSize()

The TrimToSize method changes the capacity of the ArrayList to match its current number of items.

Finally, if you want to clear all the objects out of an ArrayList and start over again, you can use the Clear method like this:

colArrayList.Clear()

The Clear method gets rid of all the current items in an ArrayList. However, it does not reset the capacity. To clear all the items and reset the capacity, you must call both the Clear and TrimToSize methods.

Adding Items to an ArrayListYou can add individual items to an ArrayList by using the Add method. For example, the following statement adds the string "Hello World!" to an ArrayList:

colArrayList.Add( "Hello World!" )

Remember that an ArrayList can contain any type of object. So, you can add integers, TextBox controls, or any weird object that you discover in the .NET framework.

When you add an object to an ArrayList, it's added to the end as the last element. You can return the index of an item that you add to an ArrayList like this:

intItemIndex = colArrayList.Add( "Hello World!" )

If this were the first item added to the ArrayList, intItemIndex would return 0; if it were the second, intItemIndex would return 1; and so on.

If you need to add multiple objects to an ArrayList at once, you can use the AddRange method. For example, the following statement adds all the items in an ArrayList named colAnotherArrayList to an ArrayList named colArrayList:

colArrayList.AddRange( colAnotherArrayList )

You also can add multiple duplicate items to an ArrayList by using the Repeat method:

colArrayList = ArrayList.Repeat( "Hello World!", 100 )

The Repeat method returns an ArrayList that contains a value repeated a certain number of times. In this case, the ArrayList would contain 100 items with the value "Hello World!".

If you need to insert an object into an ArrayList at a particular position, you can use the Insert method. For example, the following statement inserts the string "Hello World!" at the fourth index position:

colArrayList.Insert( 4, "Hello World!" )

The InsertRange method also corresponds to the AddRange method. You can use the InsertRange method, as shown here, to add multiple objects starting at a certain position:

colArrayList.InsertRange( 4, colAnotherArrayList )

This statement adds the contents of an ArrayList named colAnotherArrayList to an ArrayList named colArrayList starting at the fourth index position.

NOTE

You can use the AddRange and InsertRange methods to add other types of objects to an ArrayList as well. You can use these methods with any object that supports the ICollection interface.

You might be disappointed that you can add only single items to an ArrayList. The Add method accepts only one argument. However, this disappointment is not warranted. Remember that an ArrayList can contain any type of object. If you want to add multiple items to an ArrayList at a time, use a class with the ArrayList.

The page in Listing 24.1, for example, contains a class named Products. This class has both ProductName and Price properties.

Listing 24.1 MultiArrayList.aspx<Script Runat="Server">

Public Class Product Public ProductName As String Public Price As Decimal

In the Page_Load subroutine in Listing 24.1, an ArrayList named colArrayList is declared. Two instances of the Product class are added to the ArrayList. Finally, the ArrayList is bound to a DataList control, and the two products are displayed.

Removing Items from an ArrayListThe most straightforward method of removing an item from an ArrayList is to use the Remove method. For example, the following statement removes the item "Hello World!" from an ArrayList:

colArrayList.Remove( "Hello World!" )

If an ArrayList contains duplicate items, the first item is removed. Beware that the Remove method performs an exact comparison, so it is case sensitive. If you attempt to remove a nonexistent item, nothing horrible happens. The whole ArrayList is searched for the item, and the Remove method gives up without generating an error.

If you need to remove an ArrayList item with a certain index, you can use the RemoveAt method like this:

colArrayList.RemoveAt( 4 )

This statement removes the item with an index of 4. If the ArrayList doesn't contain an item at index position 4, an error is generated.

If you want to remove a range of items in an ArrayList, use the RemoveRange method. For example, the following statement removes three items (items 2 through 4), starting at index position 2:

colArrayList.RemoveRange( 2, 3 )

Finally, if you want to clear all the items from an ArrayList, use the Clear method like this:

colArrayList.Clear()

Remember to call the TrimToSize method after calling Clear if you want to reduce the capacity of the ArrayList to the minimum (16 items).

Iterating Through the Items in an ArrayListIf you need to loop through the contents of an ArrayList, displaying each item, you can use either a For...Each or For...Next loop.

The following For...Each loop, for example, displays all the elements in an ArrayList named colArrayList:

In both cases, you assume that the ArrayList contains strings. If the ArrayList contains items with different types of data or you are not sure about the type of data contained in the ArrayList, you can loop through it by using an Object variable like this:

Dim objItem As Object

For Each objItem in colArrayList Response.Write( objItem.ToString )Next

An Object type can accept any type of value. So, regardless of whether an ArrayList contains integers, strings, classes, or whatever, you can assign the items to an Object type.

Sorting Items in an ArrayListYou can sort the items in an ArrayList by using the Sort method. For example, the page in Listing 24.2 sorts all the elements in an ArrayList named colShoppingList.

For Each strItem in colShoppingList Response.Write( "<li>" & strItem )Next%>

The C# version of this code can be found on the CD-ROM.

In Listing 24.2, three items are added to the ArrayList: eggs, milk, and beer. When the Sort method is called, the items are sorted in alphabetical order: beer, eggs, milk.

You reverse the order in which items in an ArrayList are sorted by calling the Reverse method. This method reverses the order of all the elements in an ArrayList. For example, the page in Listing 24.3 sorts a list of random numbers and reverses the results.

For Each intItem in colArrayList Response.Write( "<li>" & intItem.ToString() )Next%>

The C# version of this code can be found on the CD-ROM.

Ten random numbers are assigned to the ArrayList in this listing. Next, the ArrayList is sorted, and the elements are reversed by calling the Reverse method.

Searching for Items in an ArrayListYou could find an element in an ArrayList by looping through all its elements until a match is found. However, this is a notoriously slow search algorithm. If an ArrayList contains thousands of elements, then, potentially, thousands of elements must be checked before a match is found.

You can perform this type of slow, linear search on an ArrayList by using the Contains method. For example, the page in Listing 24.4 uses the Contains method to find the number 53 in an ArrayList.

In Listing 24.4, 1,000 random numbers are added to the ArrayList. The Contains method determines whether the number 53 is contained in it.

Using the Contains method can be slow when you're working with large ArrayLists. Fortunately, an ArrayList supports binary searches.

If you want to perform a binary search, the ArrayList must be sorted. A binary search takes advantage of the fact that the elements in an array occur in a certain order so that a match can be found more quickly.

CAUTION

A binary search can return incorrect results if an ArrayList is not sorted.

The page in Listing 24.5 illustrates how you can use the BinarySearch method.

array as the name suggests is a sequential array of elements, whereas arraylist is list based.
array bounds are fixed and arraylist bound is dynamic.
the advantages of an array is that you can have multi-dimensions and jagged arrays, whereas the only way to achieve this in arraylist is to have an arraylist of type object and performance impact is very high.

array as the name suggests is a sequential array of elements, whereas arraylist is list based.
array bounds are fixed and arraylist bound is dynamic.
the advantages of an array is that you can have multi-dimensions and jagged arrays, whereas the only way to achieve this in arraylist is to have an arraylist of type object and performance impact is very high.

array as the name suggests is a sequential array of elements, whereas arraylist is list based.
array bounds are fixed and arraylist bound is dynamic.
the advantages of an array is that you can have multi-dimensions and jagged arrays, whereas the only way to achieve this in arraylist is to have an arraylist of type object and performance impact is very high.