The ArrayList Class |
|
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.
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.
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.
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.
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.
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: Retrieving Items From an ArrayList List |
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 |
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.
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-2016, FunctionX | |
|