Home

Built-In Collection Classes

 

Introduction to List Classes

 

Overview

Instead of creating a collection class from scratch or instead of deriving a collection, you can use one of the built-in collection classes of the .NET Framework. To support the creation of any kinds of list, the Microsoft .NET Framework provides the ArrayList and the generic List classes. 

The ArrayList class is defined in the System.Collections namespace while the generic List class is part of the System.Collections.Generic namespace. Therefore, in order to use one of these classes in your application, you can first include its namespace in the file that would perform the list-related operations.

The ArrayList class implements the IList, the ICollection, and the IEnumerable interfaces. The List class implements the generic IList<>, the generic ICollection<>, the generic IEnumerable<>, the IList, the ICollection, and the IEnumerable interfaces.

The ArrayList class is founded as follows:

Public Class ArrayList _
	Implements IList, ICollection, IEnumerable, ICloneable

The generic List class is founded as follows:

Public Class List(Of T) _
	Implements IList(Of T), ICollection(Of T),  _
	IEnumerable(Of T), IList, ICollection, IEnumerable

You can use either the ArrayList or the generic List class to create and manage values for a list. Here is an example of declaring an ArrayList variable:

Imports System.Collections

Public Class Exercise
    Private ListOfNames As ArrayList

    Private Sub Exercise_Load(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles Me.Load
        ListOfNames = New ArrayList
    End Sub
End Class

Besides the ability to create a list, both the ArrayList and the List classes have the built-in mechanism for serialization.

The default constructor allows you to create an empty list before adding values to it. If you already have an ICollection-based list, that is, a list created from a class that implements the ICollection interface, you can initialize your ArrayList list with it. To support this, the ArrayList class is equipped with the following constructor:

Public Sub New(c As ICollection)

Here is an example:

Imports System.Collections

Public Class Exercise
    Private ListOfNames As ArrayList

    Private Sub Exercise_Load(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles Me.Load
        Dim cbx As ComboBox = New ComboBox

        cbx.Items.Add("Paul Bertrand Yamaguchi")
        cbx.Items.Add("Helene Mukoko")
        cbx.Items.Add("John Hancock")
        cbx.Items.Add("Gertrude Monay")

        ListOfNames = New ArrayList(cbx.Items)
    End Sub
End Class

The Capacity of a List

After declaring an ArrayList or a List variable, it is empty. As objects are added to it, the list grows. The list can grow tremendously as you wish. The number of items of the list is managed through the memory it occupies and this memory grows as needed. The number of items that the memory allocated is currently using is represented by the Capacity property. Here is an example of accessing the ArrayList.Capacity property:

Imports System.Collections

Public Class Exercise
    Private ListOfNames As ArrayList

    Private Sub Exercise_Load(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles Me.Load
        ListOfNames = New ArrayList

        Text = "List Capacity: " & ListOfNames.Capacity
    End Sub
End Class

This would produce:

ArrayList Capacity

The capacity of a list will usually be the least of your concerns. If for some reason, you want to intervene and control the number of items that your list can contain, you can manipulate the Capacity property. For example, you can assign it a constant to set the maximum value that the list can contain. Instead of specifying the capacity after the list has been created, when declaring the list variable, you can specify its maximum capacity. To support this, both the ArrayList and the List classes are equipped with an additional constructor as follows:

Public Sub New(capacity As Integer)
Public Sub New(capacity As Integer)

Once again, you will hardly have any reason to use the Capacity property: the compiler knows what to do with it.

A Read-Only List

One of the reason for creating a list is to be able to add values to it, edit its values, retrieve a value, or delete values from it. These are the default operations. You can still limit these operations as you judge them unnecessary. For example, you may create a list and then initialize it with the values that you want the list to only have. If you do not want to have the user adding values to it, you can create the list as read-only. To do this, you can call the ArrayList.ReadOnly() method. It is overloaded with two versions as follows:

Public Shared Function ReadOnly(list As ArrayList) As ArrayList
Public Shared Function ReadOnly(list As IList) As IList

Some operations cannot be performed on a read-only list. To perform such operations, you can first find out whether an ArrayList list is read-only. This is done by checking its IsReadOnly property.

Item Addition

The primary operation performed on a list is to create one or more values. To do this, you have various alternatives. Both the ArrayList and the List classes are equipped with an Add() method. The syntax of the System.Collections.ArrayList.Add() method is:

Public Overridable Function Add(value As Object) As Integer

The syntax of the System.Collections.Generic.List.Add() method is:

Public Sub Add(item As T)

The argument of the method is the value to add to the list. If the method succeeds with the addition, it returns the position where the value was added in the list. Here are example for an ArrayList variable:

Private Sub Exercise_Load(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles Me.Load
        ListOfNames = New ArrayList

        ListOfNames.Add("Christine Kingston")
        ListOfNames.Add("Hermine Paulson")
        ListOfNames.Add("William Harrison")
        ListOfNames.Add("Ursula Morales")
        ListOfNames.Add("Evan Lancos")
End Sub

If the method fails to add the value and if you are using the ArrayList class, the compiler would throw an error. One of the errors that could result from the ArrayList's failure of this operation would be based on the fact that either a new value cannot be added to the list because the list is read-only, or the list was already full prior to adding the new value. Normally, a list can be full only if you had specified the maximum number of items it can contain using the ArrayList.Capacity property. As mentioned above, the list can be made read-only by passing its variable to the ArrayList.ReadOnly() method.

Instead of adding one values at a time, you can first create a list of values and add that whole list at once. To support this operation, both the ArrayList and the List classes are equipped with a method named AddRange.

The syntax of the ArrayList.AddRange() method is:

Public Overridable Sub AddRange(c As ICollection)

The syntax of the List.AddRange() method is:

Public Sub AddRange(collection As IEnumerable(Of T))

The ArrayList.AddRange() method takes as argument a list created from a class that implements the ICollection interface. Here is an example:

Private Sub Exercise_Load(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles Me.Load
        Dim cbx As ComboBox = New ComboBox
        cbx.Items.Add("Paul Bertrand Yamaguchi")
        cbx.Items.Add("Helene Mukoko")
        cbx.Items.Add("John Hancock")
        cbx.Items.Add("Gertrude Monay")

        ListOfNames = New ArrayList
        ListOfNames.AddRange(cbx.Items)
End Sub

The List.AddRange() method takes as argument a list created from a class that implements the generic IEnumerable interface.

The Number of Items in the List

When using a list, at any time, you should be able to know the number of items that the list contains. This information is provided by the ArrayList.Count or the List.Count property.

The Capacity and the Count properties have this in common: the value of each increases as the list grows and the same value decreases if the list shrinks. It is important to know that there are various differences between the capacity of a list and the number of items it contains:

  • Capacity is a read/write property. This means that you can assign a value to the capacity to fix the number of items that the list can contain. You can also retrieve the value of the Capacity
  • The Count property is read-only because it is used by the compiler to count the current number of values of the list and this counting is performed without your intervention

Item Retrieval

Once a list is ready, you can perform different types of operations on it. Besides adding items, one of the most regular operations performed on a list consists of locating and retrieving its values. You have various options.

To give you access to each member of their list, both the ArrayList and the List classes are equipped with the default Item property. The first value of the list has an index of 0. The second has an index of 1, and so on. 

To retrieve a single value based on its position, you can apply the parentheses of arrays to the variable. Here is an example:

Private Sub Exercise_Load(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles Me.Load
        Dim i As Integer
        ListOfNames = New ArrayList

        ListOfNames.Add("Christine Kingston")
        ListOfNames.Add("Hermine Paulson")
        ListOfNames.Add("William Harrison")
        ListOfNames.Add("Ursula Morales")
        ListOfNames.Add("Evan Lancos")

        For i = 0 To 4
            lbxNames.Items.Add(ListOfNames(i))
        Next

End Sub

ArrayList

Another issue to keep in mind is that the ArrayList.Item() property returns an Object value. Therefore, you may have to cast this value to your type of value to get it right.

Besides using the index to access a value from the list, the ArrayList and the List classes implement the IEnumerable.GetEnumerator() method. For this reason, you can use the For Each loop to access each member of the collection. Here is an example:

Private Sub Exercise_Load(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles Me.Load
        Dim strName As String
        ListOfNames = New ArrayList

        ListOfNames.Add("Christine Kingston")
        ListOfNames.Add("Hermine Paulson")
        ListOfNames.Add("William Harrison")
        ListOfNames.Add("Ursula Morales")
        ListOfNames.Add("Evan Lancos")

        For Each strName In ListOfNames
            lbxNames.Items.Add(strName)
        Next
End Sub

You can use the Item property to change a value in the list. Because the Item property is used to access an existing value from the list, the value must have been created. If you try setting the value of a non existing item, the compiler would throw an ArgumentOutOfRangeException Exception. Here is an example:

Private Sub Exercise_Load(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles Me.Load
        ListOfNames = New ArrayList

        ListOfNames(0) = "Paul Bertrand Yamaguchi"
End Sub

Notice that at the time the 0 item is accessed, it has not previous been created. This would produce:

Error

A review of the Details section shows:

System.ArgumentOutOfRangeException: Index was out of range. 
Must be non-negative and less than the size of the collection.
Parameter name: index
at System.Collections.ArrayList.set_Item(Int32 index, Object value)
at Exercise.StartForm(Object sender, EventArgs e) 
in E:\Programs\vb\Exercise1\Exercise1\Exercise.cs:line 31

This means that you can use the Item property only to change the value of a previous created item.

Checking the Existence of an Item

Instead of the parentheses that allow you to retrieve a value based on its position, you can look for a value based on its complete definition. You have various options. You can first "build" an item and ask the compiler to check whether any item in the list matches your definition. To perform this search, depending on your class, you can call either the ArrayList.Contains() or the List.Contains() method. The syntax of the System.Collections.ArrayList.Contains() method is:

Public Overridable Function Contains(item As Object) As Boolean

The syntax of the System.Collections.Generic.List.Contains() method is:

Public Function Contains(item As T) As Boolean

The value to look for is passed as argument to the method. The compiler would look for exactly the value, using its definition, in the list. If any detail of the argument fails to match any value of the list, the method would return false. If all characteristics of the argument correspond to a value of the list, the method returns true. Here is an example:

Imports System.Collections

Public Class Exercise
    Private ListOfNames As ArrayList

    Private Sub Exercise_Load(ByVal sender As Object, _
                              ByVal e As System.EventArgs) _
                              Handles Me.Load
        ListOfNames = New ArrayList

        ListOfNames.Add("Christine Kingston")
        ListOfNames.Add("Hermine Paulson")
        ListOfNames.Add("William Harrison")
        ListOfNames.Add("Ursula Morales")
        ListOfNames.Add("Evan Lancos")

        For Each strName As String In ListOfNames
            lbxNames.Items.Add(strName)
        Next
    End Sub

    Private Sub btnResult_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) _
                                Handles btnResult.Click
        Dim strFind As String = txtLookFor.Text

        If ListOfNames.Contains(strFind) = True Then
            txtResult.Text = "Found"
        Else
            txtResult.Text = "Not Found"
        End If
    End Sub
End Class
Array List
Array List

Searching for an Item

Another option to look for an item in a list consists of calling the BinarySearch() method of either the ArrayList or the List class. It is overloaded in three versions and one of them uses the following syntax:

Public Overridable Function BinarySearch(value As Object) As Integer
Public Function BinarySearch(item As T) As Integer

The value to look for is passed argument to the method. Here is an example:

Private Sub btnResult_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) _
                                Handles btnResult.Click
        Dim strFind As String = txtLookFor.Text

        If ListOfNames.BinarySearch(strFind) > 0 Then
            txtResult.Text = "Found"
        Else
            txtResult.Text = "Not Found"
        End If
End Sub

Clearing a List

To remove all items from a list at once, you can call the Clear() method of either the ArrayList or the List class. Its syntax is:

Public Overridable Sub Clear

Deleting an Item

As opposed to adding a value to a list, you may want to remove one. To perform this operation, you have various options. You can ask the compiler to look for an item in the list and if, or once, the compiler finds it, it would delete the value. To perform this type of deletion, you can call the Remove() method of either the ArrayList or the List class. Its syntax is:

Public Overridable Sub Remove(obj As Object)
Public Function Remove(item As T) As Boolean

This method accepts as argument the value that you want to delete from the list. To perform this operation, the list must not be read-only. Here is an example:

Private Sub btnDelete_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) _
                                Handles btnDelete.Click
        ListOfNames.Remove("Ursula Morales")
        lbxNames.Items.Clear()

        For Each strName As String In ListOfNames
            lbxNames.Items.Add(strName)
        Next
End Sub

The Remove() method allows you to specify the exact value you want to delete from a list. Another option you have consists of deleting a value based on its position. This is done using the RemoveAt() method whose syntax is:

Public Overridable Sub RemoveAt(index As Integer)

With this method, the position of the item is passed as argument. Here is an example:

Private Sub btnDelete_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) _
                                Handles btnDelete.Click
        ListOfNames.RemoveAt(1)
        lbxNames.Items.Clear()

        For Each strName As String In ListOfNames
            lbxNames.Items.Add(strName)
        Next
End Sub

If the position is not valid because either it is lower or higher than the current Count, the compiler would throw an ArgumentOutOfRangeException exception.

 

Home Copyright © 2008-2016, FunctionX, Inc.