Collections

Team-Fly    

 
Application Development Using Visual Basic and .NET
By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Chapter 6.  VB.NET in the .NET Framework


The .NET Framework class library provides an extensive set of classes for working with collections of objects. These classes are all in the System.Collections namespace and implement a number of different kinds of collections, including lists, queues, stacks, arrays, and hashtables. The collections contain Object instance references. Since all types derive ultimately from Object , any built-in or user -defined type may be stored in a collection.

In this section we will look at a representative class in this namespace, ArrayList , and see how to use array lists in our programs.

ArrayList Example

To get our bearings, let's begin with a simple example of using the ArrayList class. An array list, as the name suggests, is a list of items stored like an array. An array list can be dynamically sized and will grow as necessary to accommodate new elements being added.

Collection classes are made up of instances of type Object . We will create and manipulate a collection of Customer objects. We could just as easily create a collection of any other built-in or user-defined type. If our type were a value type, such as Integer , the instance would be boxed before being stored in the collection. When the object is extracted from the collection, it will be unboxed back to Integer .

Our example program is CustomerCollection . It initializes a list of customers and then lets the user show the customers, register a new customer, unregister a customer, and change an email address. A simple "help" method displays the commands that are available:

 graphics/codeexample.gif Enter command, quit to exit H> help The following commands are available:    register   register a customer    unregister unregister a customer    email      change email address    show       show customers    quit       exit the program 

Before examining the code, it would be a good idea to run the program to register a new customer, show the customers, change an email address, unregister a customer, and show the customers again. Here is a sample run of the program:

 H> show id (-1 for all): -1    1   Rocket       Squirrel    rocky@frosbitefalls.com    2   Bullwinkle   Moose       moose@wossamotta.edu H> register first name: Bob last name: Oberg email address: oberg@objectinnovations.com id = 3 H> email customer id: 1 email address: rocky@objectinnovations.com H> unregister id: 2 H> show id (-1 for all): -1    1   Rocket       Squirrel    rocky@objectinnovations.com    3   Bob          Oberg       oberg@objectinnovations.com 
Customers Class

All the code for this project is in the folder CustomerCollection . The file customer.vb has code for the Customer and Customers classes. The code for Customer is almost identical to what we looked at previously. The only addition is a special constructor that instantiates a Customer object with a specified ID. We use this constructor in the Customers class when we remove an element and when we check if an element is present in the collection.

 Public Class Customer    ...    Public Sub New(ByVal id As Integer)       CustomerId = id       FirstName = ""       LastName = ""       EmailAddress = ""    End Sub    ... End Class 

The Customers class contains a list of customers, represented by an ArrayList .

 Public Class Customers  Private m_customers As ArrayList  Public Sub New()       m_customers = New ArrayList()       RegisterCustomer(_          "Rocket", _          "Squirrel", _          "rocky@frosbitefalls.com")       RegisterCustomer(_          "Bullwinkle", _          "Moose", _          "moose@wossamotta.edu")    End Sub    Public Function RegisterCustomer(_     ByVal firstName As String, _     ByVal lastName As String, _     ByVal emailAddress As String) As Integer       Dim cust As Customer = New Customer(_          firstName, lastName, emailAddress)  m_customers.Add(cust)  Return cust.CustomerId    End Function    Public Function UnregisterCustomer(_     ByVal id As Integer)       Dim cust As Customer = New Customer(id)  m_customers.Remove(cust)  End Function    Public Sub ChangeEmailAddress(_     ByVal id As Integer, _     ByVal emailAddress As String)       Dim cust As Customer  For Each cust In m_customers  If cust.CustomerId = id Then             cust.EmailAddress = emailAddress             Return          End If       Next       Throw New Exception("id " & id & " not found")    End Sub    Public Sub ShowCustomers(ByVal id As Integer)       If Not CheckId(id) And id <> -1 Then          Return       End If       Dim cust As Customer  For Each cust In m_customers  If (id = -1 Or id = cust.CustomerId) Then             Dim sid As String = _                 cust.CustomerId.ToString().PadLeft(4)             Dim first As String = _                 cust.FirstName.PadRight(12)             Dim last As String = _                 cust.LastName.PadRight(12)             Dim email As String = _                 cust.EmailAddress.PadRight(20)             Dim str As String = _             sid & "   " & first & "   " & _                     last & "   " & email             Console.WriteLine(str)          End If       Next    End Sub    Private Function CheckId(ByVal id As Integer) _     As Boolean       Dim cust As Customer = New Customer(id)  Return m_customers.Contains(cust)  End Function End Class 

The bold lines in the listing show the places where we are using collection class features. In Chapter 4 we have already used For Each with arrays. The reason For Each can be used with arrays is that the Array class, like ArrayList , implements the IEnumerable interface that provides the foundation for the For Each syntax. We will discuss IEnumerable and the other collection interfaces later in this chapter.

The Add and Remove methods , as their names suggest, are used for adding and removing elements from a collection. The Remove method searches for an object in the collection that Equals the object passed as a parameter. Our special constructor creates an object having the id of the element we want to remove. Since we provided an override of the Equals method that bases equality on CustomerId , the proper element will be removed.

Similarly, the Contains method used in our CheckId helper method also relies on the override of the Equals method.

Compare the code in this program with the use of arrays in the code in the previous chapter's case study. The collection code is much simpler. Using collections makes it easy to remove elements as well as add them. Using arrays, you would have to write special code to move array elements to fill in the space where an element was deleted. Also, collections are not declared to have a specific size , but can grow as required.


Team-Fly    
Top
 


Application Development Using Visual BasicR and .NET
Application Development Using Visual BasicR and .NET
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 190

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net