Home

The ArrayList Class

 

Introduction

To support arrays of any kind, the Microsoft .NET Framework provides the ArrayList class. This class can be used to add, locate, or remove an item from a list. The class provides many other valuable operations routinely done on a list. Because of its flexibility, ArrayList is the most used class to create lists of items of any kind in a .NET application.

The ArrayList class is defined in the System.Collections namespace. Therefore, in order to use the ArrayList class in your application, you must first include the System.Collections namespace in the file that would perform ArrayList operations.

 

Practical Learning Practical Learning: Introducing the ArrayList Class

  1. Start a new file in Notepad and type type the following:
     
    Interface IStockItem
        Property PartNumber() As String
        Property PartName() As String
        Property UnitPrice() As Double
    End Interface
    
    Public Class Part
        Implements IStockItem
    
        Private ID As String
        Protected name As String
        Protected price As Decimal
        Private qty As Integer
    
        Public Sub New()
            ID = ""
            name = "Unknown"
            price = 0.0
        End Sub
    
        Public Sub New(ByVal Nbr As String, ByVal nm As String, ByVal pr As Double)
            ID = Nbr
            name = nm
            price = pr
        End Sub
    
        Public Sub New(ByVal Nbr As String, ByVal nm As String, _
                        ByVal quantity As Integer, ByVal pr As Double)
            ID = Nbr
            name = nm
            quantity = qty
            price = pr
        End Sub
    
        Public Property PartName() As String Implements IStockItem.PartName
            Get
                Return ID
            End Get
            Set(ByVal Value As String)
                ID = Value
            End Set
        End Property
    
        Public Property PartNumber() As String Implements IStockItem.PartNumber
            Get
                Return name
            End Get
            Set(ByVal Value As String)
                name = Value
            End Set
        End Property
    
        Public Property UnitPrice() As Double Implements IStockItem.UnitPrice
            Get
                Return price
            End Get
            Set(ByVal Value As Double)
                price = Value
            End Set
        End Property
    
        Public Property Quantity() As Integer
            Get
                Return qty
            End Get
            Set(ByVal Value As Integer)
                qty = Value
            End Set
        End Property
    End Class
  2. On the main menu, click File -> New
  3. When asked whether you want to save the changes, click Yes
  4. Locate your VBasic folder and display it in the Save In combo box
  5. Create a new folder named AutoParts2
  6. Change the Save As Type to All Files
  7. Set the file name to Parts.vb and click Save
  8. In the new empty file of Notepad, type the following:
     
    Imports System
    imports System.Collections
    
    Public Class OrderProcessing
    
        Dim ListOfParts As ArrayList
    
        Public Sub New()
    
            ListOfParts = New ArrayList
        End Sub
    
        Public Sub CreateInventory()
    
        End Sub
    
        Public Sub AddNewItem()
    
        End Sub
    
        Public Sub ShowInventory()
    
        End Sub
    
        Public Sub ProcessOrder()
    
        End Sub
    
        Public Sub DisplayReceipt()
    
        End Sub
    End Class
  9. To save the file, on the main menu, click File -> Save
  10. Make sure the AutoParts2 folder is displaying in the Save In combo box
  11. Change the Save As Type to All Files. Set the File Name to OrderProcessing.vb  and press Enter
  12. Start a new file and type the following:
     
    Imports System
    
    Public Class Exercise
        Public Shared Sub main()
            Dim order As OrderProcessing = New OrderProcessing
        End Sub
    End Class
  13. Save the new file as Exercise.vb in the AutoParts2 folder
  14. Open Windows Explorer or My Computer
 

The Capacity of a List

After declaring an ArrayList 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 ArrayList.Capacity property. This will usually be the least of your concerns.

If for some reason, you want to intervene and control the number of items that your ArrayList 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. Once, you will hardly have any reason to use the Capacity property: the compiler knows what to do with it.

If you set a fixed size on an ArrayList list, you may not be able to add a new item beyond the limit. In fact, if you attempt to do this, you may receive an error. A safe way is to check whether the list is fixed before performing a related operation. To find out whether a list is fixed, you can check the ArrayList variable's IsFixedSize property.

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 property. The Capacity and the Count 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, although they look alike, 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, as we saw above, 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 is read-only because it is used by the compiler to count the current number of items of the items and this counting is performed without your intervention.

A Read-Only List

One of the reason for creating a list is to be able to add items to it, edit its items, retrieve an items, or delete items 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 items that you want the list to only have. If you don't intend to have the user adding items 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:

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

This method is static. This means that you don't need to declare an instance of ArrayList to call them. Instead, to make the list read-only, call the ArrayList.ReadOnly() method and pass your ArrayList variable to it.

As we will see in the next sections, 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. One of the biggest advantages of using a linked list is that you don't have to specify in advance the number of items of the list as done for an array. You can just start adding items. The ArrayList class makes this possible with the Add() method. Its syntax is:

Public Overridable Function Add( _
   ByVal value As Object _
) As Integer Implements IList.Add

The argument of this 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. This is usually the last position in the list. If the method fails, the compiler would throw an error. One of the errors that could result from failure of this operation would be based on the fact that either a new item cannot be added to the list because the list is read-only, or the list was already full prior to adding the new item. 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.

 

Practical Learning Practical Learning: Adding Items to an ArrayList List

  1. To create an inventory, access the OrderProcessing.vb file and change it as follows:
     
    Imports System
    imports System.Collections
    
    Public Class OrderProcessing
    
        Dim ListOfParts As ArrayList
    
        Public Sub New()
    
            ListOfParts = New ArrayList
        End Sub
    
        Public Sub CreateInventory()
            Dim One As Part
    
            ' Create a Part object using its properties
            One = New Part
            One.PartNumber = "GD646"
            One.PartName = "Bearing Clutch Pilot  "
            One.UnitPrice = 9.75
            One.Quantity = 4
            ' Add the new part to the list
            ListOfParts.Add(One)
    
            ' Create a Part object using a constructor
            One = New Part("EU473", "Belt Accessory Drive  ", 6.75)
            One.Quantity = 10
            ' Add the new part to the list
            ListOfParts.Add(One)
    
            ' Do the same to complete the list
            One = New Part("AH325", "Break Drum            ", 20.55)
            One.Quantity = 5
            ListOfParts.Add(One)
            One = New Part("KS745", "Right Mirror          ", 9.35)
            One.Quantity = 2
            ListOfParts.Add(One)
            One = New Part("KE374", "Break Shoe            ", 20.25)
            One.Quantity = 6
            ListOfParts.Add(One)
            One = New Part("GD943", "Signal Lamp Assembly  ", 74.55)
            One.Quantity = 4
            ListOfParts.Add(One)
            One = New Part("GH386", "Bearing Input Shaft   ", 45.25)
            One.Quantity = 3
            ListOfParts.Add(One)
            One = New Part("WD394", "Brake Disc            ", 85.5)
            One.Quantity = 14
            ListOfParts.Add(One)
            One = New Part("TR944", "Front Wheel Lug Nut   ", 10.75)
            One.Quantity = 7
            ListOfParts.Add(One)
            One = New Part("GD844", "Front Pump Gasket     ", 10.75)
            One.Quantity = 6
            ListOfParts.Add(One)
            One = New Part("GD933", "Filter Steering       ", 12.55)
            One.Quantity = 4
            ListOfParts.Add(One)
            One = New Part("GW478", "Air Control Valve     ", 35.25)
            One.Quantity = 8
            ListOfParts.Add(One)
            One = New Part("LA943", "Clutch Master Clndr   ", 124.55)
            One.Quantity = 5
            ListOfParts.Add(One)
            One = New Part("RU688", "Tie Rod               ", 32.55)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("PP797", "Ball Joint            ", 25.75)
            One.Quantity = 14
            ListOfParts.Add(One)
            One = New Part("RA292", "Drive Belt            ", 10.65)
            One.Quantity = 10
            ListOfParts.Add(One)
            One = New Part("AG778", "Oil Filter            ", 6.25)
            One.Quantity = 6
            ListOfParts.Add(One)
            One = New Part("KQ820", "Timing Belt           ", 45.95)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("GT722", "Intake Manifold Gask  ", 18.55)
            One.Quantity = 4
            ListOfParts.Add(One)
            One = New Part("WA502", "Spark Plug Seal       ", 4.15)
            One.Quantity = 24
            ListOfParts.Add(One)
            One = New Part("AL848", "Air Filter            ", 15.65)
            One.Quantity = 32
            ListOfParts.Add(One)
            One = New Part("RU382", "Fuel Injector Clip    ", 17.05)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("HJ624", "Brk Caliper w/o Pads  ", 190.5)
            One.Quantity = 3
            ListOfParts.Add(One)
            One = New Part("RL555", "Crankshaft Seal       ", 10.55)
            One.Quantity = 7
            ListOfParts.Add(One)
            One = New Part("PQ273", "Oil Pump              ", 218.75)
            One.Quantity = 16
            ListOfParts.Add(One)
            One = New Part("ER162", "Timing Belt Tensioner ", 264.55)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("EY275", "Camshaft Seal         ", 8.95)
            One.Quantity = 8
            ListOfParts.Add(One)
            One = New Part("LM357", "Valve Cover Gasket    ", 22.75)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("RU473", "Valve Stem Seal       ", 3.95)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("QW374", "Starter               ", 320.65)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("QR374", "Radiator Cap          ", 12.75)
            One.Quantity = 14
            ListOfParts.Add(One)
            One = New Part("PQ902", "Thermostat Gasket     ", 4.2)
            One.Quantity = 9
            ListOfParts.Add(One)
            One = New Part("QT847", "Water Pump            ", 12.95)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("PY784", "Spark Plug Platinum   ", 145.85)
            One.Quantity = 14
            ListOfParts.Add(One)
            One = New Part("TQ483", "Tie Rod Assembly      ", 3.95)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("EQ173", "Oil Pump              ", 155.75)
            One.Quantity = 20
            ListOfParts.Add(One)
            One = New Part("UG376", "Piston Ring Set       ", 218.75)
            One.Quantity = 13
            ListOfParts.Add(One)
            One = New Part("PI489", "Distributor Cap       ", 275.55)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("BT389", "Oil Seal Front Pump   ", 7.05)
            One.Quantity = 18
            ListOfParts.Add(One)
            One = New Part("CQ274", "Transmitter Filter Kit", 9.25)
            One.Quantity = 22
            ListOfParts.Add(One)
            One = New Part("QX202", "Tail Lamp Assembly    ", 5.05)
            One.Quantity = 7
            ListOfParts.Add(One)
            One = New Part("GN780", "Bearing Wheel         ", 40.15)
            One.Quantity = 5
            ListOfParts.Add(One)
            One = New Part("XZ485", "Left Mirror           ", 7.25)
            One.Quantity = 8
            ListOfParts.Add(One)
            One = New Part("BD199", "Caliper Bolt/Pin      ", 3.55)
            One.Quantity = 8
            ListOfParts.Add(One)
        End Sub
    
        Public Sub AddNewItem()
            
        End Sub
    
        Public Sub ShowInventory()
            
        End Sub
    
        Public Sub ProcessOrder()
    
        End Sub
    
        Public Sub DisplayReceipt()
    
        End Sub
    End Class
  2. Save the file
  3. To test the above code, access the Exercise.vb file and change it as follows:
     
    Imports System
    
    Public Class Exercise
        Public Shared Sub main()
            Dim order As OrderProcessing = New OrderProcessing
            Dim Choice As Integer
            order.CreateInventory()
    
            ' Display a short menu to the user before taking an action
            Try
                Console.WriteLine(" =-= College Park Auto Parts =-=")
                Console.WriteLine("How may I help you?")
                Console.WriteLine("1. I want to process a customer's order")
                Console.WriteLine("2. I want to see the current inventory")
                Console.WriteLine("3. I want to add a new item to the inventory")
                Console.Write("Your choice (1, 2, or 3)? ")
                Choice = CInt(Console.ReadLine())
            Catch ex As InvalidCastException
              Console.WriteLine("\nInvalid Choice - The program will terminate\n")
            End Try
    
            ' Take an action based on the user's choice
            Select Case Choice
                Case 1
                    order.ProcessOrder()
                Case 2
                    order.ShowInventory()
                Case 3
                    order.AddNewItem()
            End Select
    
        End Sub
    End Class
  4. Save the file
  5. Access the Command Prompt and change to the AutoParts2 folder
  6. To compile the application, vbc / out:"Four-Corner Auto-Parts R2".exe OrderProcessing.vb Exercise.vb and press Enter
  7. To execute the application, type "Four-Corner Auto-Parts R2" and press Enter. Here is an example:
     
    =-= College Park Auto Parts =-=
    How may I help you?
    1. I want to process a customer's order
    2. I want to see the current inventory
    3. I want to add a new item to the inventory
    Your choice (1, 2, or 3)? 2
    
    ===============================================
    =-= College Park Auto Parts =-= Store Inventory
    -----------------------------------------------
     Item #  Description               Price   Qty
     GD646   Bearing Clutch Pilot       9.75    4
     EU473   Belt Accessory Drive       6.75   10
     AH325   Break Drum                20.55    5
     KS745   Right Mirror               9.35    2
     KE374   Break Shoe                20.25    6
     GD943   Signal Lamp Assembly      74.55    4
     GH386   Bearing Input Shaft       45.25    3
     WD394   Brake Disc                 85.5   14
     TR944   Front Wheel Lug Nut       10.75    7
     GD844   Front Pump Gasket         10.75    6
     GD933   Filter Steering           12.55    4
     GW478   Air Control Valve         35.25    8
     LA943   Clutch Master Clndr      124.55    5
     RU688   Tie Rod                   32.55   12
     PP797   Ball Joint                25.75   14
     RA292   Drive Belt                10.65   10
     AG778   Oil Filter                 6.25    6
     KQ820   Timing Belt               45.95    1
     GT722   Intake Manifold Gask      18.55    4
     WA502   Spark Plug Seal            4.15   24
     AL848   Air Filter                15.65   32
     RU382   Fuel Injector Clip        17.05   12
     HJ624   Brk Caliper w/o Pads      190.5    3
     RL555   Crankshaft Seal           10.55    7
     PQ273   Oil Pump                 218.75   16
     ER162   Timing Belt Tensioner    264.55   12
     EY275   Camshaft Seal              8.95    8
     LM357   Valve Cover Gasket        22.75    1
     RU473   Valve Stem Seal            3.95    1
     QW374   Starter                  320.65    1
     QR374   Radiator Cap              12.75   14
     PQ902   Thermostat Gasket           4.2    9
     QT847   Water Pump                12.95   12
     PY784   Spark Plug Platinum      145.85   14
     TQ483   Tie Rod Assembly           3.95   12
     EQ173   Oil Pump                 155.75   20
     UG376   Piston Ring Set          218.75   13
     PI489   Distributor Cap          275.55    1
     BT389   Oil Seal Front Pump        7.05   18
     CQ274   Transmitter Filter Kit     9.25   22
     QX202   Tail Lamp Assembly         5.05    7
     GN780   Bearing Wheel             40.15    5
     XZ485   Left Mirror                7.25    8
     BD199   Caliper Bolt/Pin           3.55    8
    ===============================================
  8. After testing the program, return to Notepad

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 items. You have various options. To retrieve a single item based on its position, you can apply the square brackets of arrays to the variable. Like a normal array, an ArrayList list is zero-based. Another issue to keep in mind is that the ArrayList returns an Object value. Therefore, you may have to cast this value to your type of value to get it right.

 

Practical Learning Practical Learning: Retrieving Items From an ArrayList List

  1. To show an inventory, access the WorkOrder.vb file and change it as follows:
     
    Imports System
    imports System.Collections
    
    Public Class OrderProcessing
    
        Dim ListOfParts As ArrayList
    
        Public Sub New()
    
            ListOfParts = New ArrayList
        End Sub
    
        Public Sub CreateInventory()
            Dim One As Part
    
            ' Create a Part object using its properties
            One = New Part
            One.PartNumber = "GD646"
            One.PartName = "Bearing Clutch Pilot  "
            One.UnitPrice = 9.75
            One.Quantity = 4
            ' Add the new part to the list
            ListOfParts.Add(One)
    
            ' Create a Part object using a constructor
            One = New Part("EU473", "Belt Accessory Drive  ", 6.75)
            One.Quantity = 10
            ' Add the new part to the list
            ListOfParts.Add(One)
    
            ' Do the same to complete the list
            One = New Part("AH325", "Break Drum            ", 20.55)
            One.Quantity = 5
            ListOfParts.Add(One)
            One = New Part("KS745", "Right Mirror          ", 9.35)
            One.Quantity = 2
            ListOfParts.Add(One)
            One = New Part("KE374", "Break Shoe            ", 20.25)
            One.Quantity = 6
            ListOfParts.Add(One)
            One = New Part("GD943", "Signal Lamp Assembly  ", 74.55)
            One.Quantity = 4
            ListOfParts.Add(One)
            One = New Part("GH386", "Bearing Input Shaft   ", 45.25)
            One.Quantity = 3
            ListOfParts.Add(One)
            One = New Part("WD394", "Brake Disc            ", 85.5)
            One.Quantity = 14
            ListOfParts.Add(One)
            One = New Part("TR944", "Front Wheel Lug Nut   ", 10.75)
            One.Quantity = 7
            ListOfParts.Add(One)
            One = New Part("GD844", "Front Pump Gasket     ", 10.75)
            One.Quantity = 6
            ListOfParts.Add(One)
            One = New Part("GD933", "Filter Steering       ", 12.55)
            One.Quantity = 4
            ListOfParts.Add(One)
            One = New Part("GW478", "Air Control Valve     ", 35.25)
            One.Quantity = 8
            ListOfParts.Add(One)
            One = New Part("LA943", "Clutch Master Clndr   ", 124.55)
            One.Quantity = 5
            ListOfParts.Add(One)
            One = New Part("RU688", "Tie Rod               ", 32.55)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("PP797", "Ball Joint            ", 25.75)
            One.Quantity = 14
            ListOfParts.Add(One)
            One = New Part("RA292", "Drive Belt            ", 10.65)
            One.Quantity = 10
            ListOfParts.Add(One)
            One = New Part("AG778", "Oil Filter            ", 6.25)
            One.Quantity = 6
            ListOfParts.Add(One)
            One = New Part("KQ820", "Timing Belt           ", 45.95)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("GT722", "Intake Manifold Gask  ", 18.55)
            One.Quantity = 4
            ListOfParts.Add(One)
            One = New Part("WA502", "Spark Plug Seal       ", 4.15)
            One.Quantity = 24
            ListOfParts.Add(One)
            One = New Part("AL848", "Air Filter            ", 15.65)
            One.Quantity = 32
            ListOfParts.Add(One)
            One = New Part("RU382", "Fuel Injector Clip    ", 17.05)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("HJ624", "Brk Caliper w/o Pads  ", 190.5)
            One.Quantity = 3
            ListOfParts.Add(One)
            One = New Part("RL555", "Crankshaft Seal       ", 10.55)
            One.Quantity = 7
            ListOfParts.Add(One)
            One = New Part("PQ273", "Oil Pump              ", 218.75)
            One.Quantity = 16
            ListOfParts.Add(One)
            One = New Part("ER162", "Timing Belt Tensioner ", 264.55)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("EY275", "Camshaft Seal         ", 8.95)
            One.Quantity = 8
            ListOfParts.Add(One)
            One = New Part("LM357", "Valve Cover Gasket    ", 22.75)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("RU473", "Valve Stem Seal       ", 3.95)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("QW374", "Starter               ", 320.65)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("QR374", "Radiator Cap          ", 12.75)
            One.Quantity = 14
            ListOfParts.Add(One)
            One = New Part("PQ902", "Thermostat Gasket     ", 4.2)
            One.Quantity = 9
            ListOfParts.Add(One)
            One = New Part("QT847", "Water Pump            ", 12.95)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("PY784", "Spark Plug Platinum   ", 145.85)
            One.Quantity = 14
            ListOfParts.Add(One)
            One = New Part("TQ483", "Tie Rod Assembly      ", 3.95)
            One.Quantity = 12
            ListOfParts.Add(One)
            One = New Part("EQ173", "Oil Pump              ", 155.75)
            One.Quantity = 20
            ListOfParts.Add(One)
            One = New Part("UG376", "Piston Ring Set       ", 218.75)
            One.Quantity = 13
            ListOfParts.Add(One)
            One = New Part("PI489", "Distributor Cap       ", 275.55)
            One.Quantity = 1
            ListOfParts.Add(One)
            One = New Part("BT389", "Oil Seal Front Pump   ", 7.05)
            One.Quantity = 18
            ListOfParts.Add(One)
            One = New Part("CQ274", "Transmitter Filter Kit", 9.25)
            One.Quantity = 22
            ListOfParts.Add(One)
            One = New Part("QX202", "Tail Lamp Assembly    ", 5.05)
            One.Quantity = 7
            ListOfParts.Add(One)
            One = New Part("GN780", "Bearing Wheel         ", 40.15)
            One.Quantity = 5
            ListOfParts.Add(One)
            One = New Part("XZ485", "Left Mirror           ", 7.25)
            One.Quantity = 8
            ListOfParts.Add(One)
            One = New Part("BD199", "Caliper Bolt/Pin      ", 3.55)
            One.Quantity = 8
            ListOfParts.Add(One)
        End Sub
    
        Public Sub AddNewItem()
            Dim ID As String, Name As String
            Dim Price As Double
            Dim qty As Integer
    
            ' Ask the user to type a number for the new part
            Console.Write("Enter Item Number (Example: PD764): ")
            ID = Console.ReadLine()
            ' Then ask the user to provide additional information about the part
            Console.WriteLine("Enter the name or a short description: ")
            Name = Console.ReadLine()
            Console.Write("Enter Unit Price: ")
            Price = Decimal.Parse(Console.ReadLine())
            Console.Write("How Many? ")
            qty = CInt(Console.ReadLine())
    
            ' Using the new information that the user provided
            ' Create a new Part object using the second constructor
            Dim NewPart As Part = New Part(ID, Name, qty, Price)
    
            ' Once the part is ready, add it to the database
            ListOfParts.Add(NewPart)
    
            ShowInventory()
        End Sub
    
        Public Sub ShowInventory()
            Console.WriteLine(vbCrLf & "===============================================")
            Console.WriteLine("=-= College Park Auto Parts =-= Store Inventory")
            Console.WriteLine("-----------------------------------------------")
            Console.WriteLine(" Item #  Description               Price   Qty")
            For Each one As Part In ListOfParts
                Console.WriteLine(" {0}   {1}   {2,6}{3,5}", _
                 one.PartNumber, one.PartName, _
                 one.UnitPrice, one.Quantity)
            Next
    
            Console.WriteLine("===============================================")
        End Sub
    
        Public Sub ProcessOrder()
            Dim Choices As ArrayList = New ArrayList
            Dim AnItem As Part
            Dim PartID As String
            Dim Qty As Integer
    
            Do
                Console.Write("Enter the part number (q to stop): ")
                PartID = Console.ReadLine()
    
                For Each item As Part In ListOfParts
                    If PartID = item.PartNumber Then
                        AnItem.PartNumber = item.PartNumber
                        AnItem.PartName = item.PartName
                        AnItem.UnitPrice = item.UnitPrice
    
                        Try
                            Console.Write("How many? ")
                            Qty = CInt(Console.ReadLine())
                            item.Quantity = Qty
    
                        Catch ex As InvalidCastException
                            Console.WriteLine("Invalid Quantity!!!")
    
                            Choices.Add(AnItem)
                        End Try
                    End If
                Next
            Loop While PartID <> "q" And PartID <> "Q"
    
            DisplayReceipt(Choices)
        End Sub
    
        Public Sub DisplayReceipt(ByVal lstItems As ArrayList)
            Dim SubTotal As Double, TotalOrder As Double
    
            Console.WriteLine("========================================================")
            Console.WriteLine("=-= College Park Auto Parts =-= Receipt")
            Console.WriteLine("------+---+-------------------------+-------+-----------")
            Console.WriteLine("Part#  Qty  Description               Price   SubTotal")
            Console.WriteLine("------+---+-------------------------+-------+-----------")
    
            For Each One As Part In lstItems
                SubTotal = One.UnitPrice * One.Quantity
                TotalOrder += SubTotal
    
                Console.WriteLine("{0}   {1}   {2}    {3,6}    {4,6}", _
                               One.PartNumber, One.Quantity, One.PartName, _
                               One.UnitPrice, SubTotal)
            Next
    
            Console.WriteLine("------+---+-------------------------+-------+-----------")
            Console.WriteLine("Total Order: {0:C}", TotalOrder)
            Console.WriteLine("========================================================" & vbCrLf)
        End Sub
    End Class
  2. Save, compile, and test the program.
  3. Return to Notepad

Item Location

Instead of the square brackets that allow you to retrieve an item based on its position, you can look for an item 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, you can call the ArrayList.Contains() method. Its syntax is:

Public Overridable Function Contains( _
   ByVal item As Object _
) As Boolean Implements IList.Contains

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

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

Overloads Public Overridable Function BinarySearch( _
   ByVal value As Object _
) As Integer

The item to look for is passed argument to the method.

Item Deletion

As opposed to adding an item 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 compile finds it, it would delete the item. To perform this type of deletion, you can call the ArrayList.Remove() method. Its syntax is:

Public Overridable Sub Remove( _
   ByVal obj As Object _
) Implements IList.Remove

This method accepts as argument the item that you want to delete from the list. To perform this operation, the list must not be read-only.

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

Public Overridable Sub RemoveAt( _
   ByVal index As Integer _
) Implements IList.RemoveAt

With this method, the position of the item is passed as argument. If the position is not valid because either it is lower or higher than the current Count, the compiler would throw an ArgumentOutOfRangeException exception.

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

Public Overridable Sub Clear() Implements IList.Clear

 

 

Home Copyright © 2005-2012 FunctionX