Introduction to Collections |
|
As we have used so far, an array is primarily a variable. As such, it can be declared as a member of a class. To do this, you can declare it like a normal array in the body of the class. Here is an example: Public Class NumberCrunching Dim Number(4) As Double End Class
Like any member variable, when an array has been declared as a member variable, it is made available to all the other members of the same class. You can use this feature to initialize the array in one method and let other methods use the initialized variable. This also means that you don't have to pass the array as argument nor do you have to explicitly return it from a method. If you plan to use the array as soon as the program is running, you can initialize it using a constructor or a method that you know would be called before the array is used. Here is an example: Public Class NumberCrunching Dim Number(4) As Double Public Sub New() Number(0) = 12.44 Number(1) = 525.38 Number(2) = 6.28 Number(3) = 2448.32 Number(4) = 632.04 End Sub End Class After an array is made a member variable, it can be used by any other member of the same class. Based on this, you can use a member of the same class to request values that would initialize it. You can also use another method to explore the array. Here is an example: Public Class NumberCrunching Dim Number(4) As Double Public Sub New() Number(0) = 12.44 Number(1) = 525.38 Number(2) = 6.28 Number(3) = 2448.32 Number(4) = 632.04 End Sub Public Sub DisplayNumber() For i As Integer = 0 To 4 Step 1 Console.WriteLine("Number {0}: {1}", i, Number(i)) Next End Sub End Class This program can be tested with the following: Imports System Public Class Exercise Public Shared Sub Main() Dim lstNumber As NumberCrunching = New NumberCrunching lstNumber.DisplayNumber() Console.WriteLine() End Sub End Class This would produce: Number 0: 12.44 Number 1: 525.38 Number 2: 6.28 Number 3: 2448.32 Number 4: 632.04 |
|
A Class as an Array Member Variable |
To use a class as an array member variable, declare the array as we have used them so far. For example, imagine you have created a class as follows: Imports System Public Class Square Private _side As Double Public Sub New() _side = 0 End Sub Public Property Side() As Double Get Return _side End Get Set(ByVal Value As Double) _side = Value End Set End Property Public ReadOnly Property Perimeter() As Double Get Return _side * 4 End Get End Property Public ReadOnly Property Area() As Double Get Return _side * _side End Get End Property End Class If the array will be declared as a member of the main class, you should (must) make it Shared. Here is how you can declare an array variable from the above class: Public Class Exercise Shared Sq(2) As Square Public Shared Sub Main() End Sub End Class After declaring the array, you can initialize it using the Main() procedure. You should first allocate memory using the New operator for each member of the array. Each member of the array is accessed using its index. Once the array exists, you can access each member of the class indirectly from the index of the variable. Here is an example: |
Imports System Public Class Square Private _side As Double Public Sub New() _side = 0 End Sub Public Property Side() As Double Get Return _side End Get Set(ByVal Value As Double) _side = Value End Set End Property Public ReadOnly Property Perimeter() As Double Get Return _side * 4 End Get End Property Public ReadOnly Property Area() As Double Get Return _side * _side End Get End Property End Class Public Class Exercise Shared Sq(2) As Square Public Shared Sub Main() Sq(0) = New Square Sq(0).Side = 18.84 Sq(1) = New Square Sq(1).Side = 25.62 Console.WriteLine("Squares Characteristics") Console.WriteLine(vbCrLf & "First Square") Console.WriteLine("Side: {0}", Sq(0).Side) Console.WriteLine("Perimeter: {0}", Sq(0).Perimeter) Console.WriteLine("Area: {0}", Sq(0).Area) Console.WriteLine(vbCrLf & "Second Square") Console.WriteLine("Side: {0}", Sq(1).Side) Console.WriteLine("Perimeter: {0}", Sq(1).Perimeter) Console.WriteLine("Area: {0}", Sq(1).Area) End Sub End Class
This would produce:
Squares Characteristics First Square Side: 18.84 Perimeter: 75.36 Area: 354.9456 Second Square Side: 25.62 Perimeter: 102.48 Area: 656.3844
If the array variable will be made a member of the non-main class, after declaring it, you can initialize it in a procedure you know would be called first, which is usually the constructor. |
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 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 |
Public Class PartsList Public Shared ItemNumber() As String = { _ "GD646", "EU473", "AH325", "KS745", "KE374", "GD943", _ "GH386", "WD394", "TR944", "GD844", "GD933", "GW478", _ "LA943", "RU688", "PP797", "RA292", "AG778", "KQ820", _ "GT722", "WA502", "AL848", "RU382", "HJ624", "RL555", _ "PQ273", "ER162", "EY275", "LM357", "RU473", "QW374", _ "QR374", "PQ902", "QT847", "PY784", "TQ483", "EQ173", _ "UG376", "PI489", "BT389", "CQ274", "QX202", "GN780", _ "XZ485", "BD199"} public Shared Description() as string = { _ "Bearing Clutch Pilot ", "Belt Accessory Drive ", _ "Break Drum ", "Right Mirror ", _ "Break Shoe ", "Signal Lamp Assembly ", _ "Bearing Input Shaft ", "Brake Disc ", _ "Front Wheel Lug Nut ", "Front Pump Gasket ", _ "Filter Steering ", "Air Control Valve ", _ "Clutch Master Clndr ", "Tie Rod ", _ "Ball Joint ", "Drive Belt ", _ "Oil Filter ", "Timing Belt ", _ "Intake Manifold Gask ", "Spark Plug Seal ", _ "Air Filter ", "Fuel Injector Clip ", _ "Brk Caliper w/o Pads ", "Crankshaft Seal ", _ "Oil Pump ", "Timing Belt Tensioner ", _ "Camshaft Seal ", "Valve Cover Gasket ", _ "Valve Stem Seal ", "Starter ", _ "Radiator Cap ", "Thermostat Gasket ", _ "Water Pump ", "Spark Plug Platinum ", _ "Tie Rod Assembly ", "Oil Pump ", _ "Piston Ring Set ", "Distributor Cap ", _ "Oil Seal Front Pump ", "Transmitter Filter Kit", _ "Tail Lamp Assembly ", "Bearing Wheel ", _ "Left Mirror ", "Caliper Bolt/Pin " } Public Shared Price() As Double = { _ 9.75, 6.75, 20.55, 9.35, 20.25, 74.55, 45.25, 85.5, _ 1.75, 0.75, 1.55, 35.25, 124.55, 32.55, 25.75, 10.65, _ 6.25, 45.95, 18.55, 4.15, 15.65, 17.05, 190.5, 10.55, _ 218.75, 264.55, 8.95, 22.75, 3.95, 320.65, 12.75, 4.2, _ 12.95, 145.85, 3.95, 155.75, 218.75, 275.55, 7.05, 9.25, _ 5.05, 40.15, 7.25, 3.55} End Class |
Public Class ListOfParts ' Because we are going to create an array-based list, ' we will use this constant as its dimension Const MaxItems As Integer = 100 ' This will help us keep track on the number of items in the list Private SizeOfList As Integer ' This method is used to add a new item to the list of auto parts Public Sub Add(ByVal P As Part) ' Increase the count of items of the list SizeOfList = SizeOfList + 1 End Sub ' This method simply returns an item from the array, ' using a specified index Public Function Retrieve(ByVal n As Integer) As Part End Function ' This method returns the current number of items in the list Public Function Count() As Integer Return SizeOfList End Function ' Default Constructor: Used to initialize an object Public Sub ListOfParts() ' When this class is primarily accessed, we want to indicate that ' its list is empty SizeOfList = 0 End Sub End Class |
Imports System Public Class Exercise Public Shared Sub main() End Sub End Class |
Public Class ListCreator ' Because we are going to create an array-based list, ' we will use this constant as its dimension Const MaxItems As Integer = 100 ' An object declared as array Dim Item(MaxItems) As Part ' This will help us keep track on the number of items in the list Private SizeOfList As Integer ' This method is used to add a new item to the list of auto parts Public Sub Add(ByVal P As Part) ' Before adding a new item, first make sure that we still have room If SizeOfList < MaxItems Then ' If we still have room, add the new item to the array Item(SizeOfList) = P ' Increase the count of items of the list SizeOfList = SizeOfList + 1 End If End Sub ' This method simply returns an item from the array, ' using a specified index Public Function Retrieve(ByVal n As Integer) As Part ' This method simply return an item from the array, using a specified index Return Item(n) End Function ' This method returns the current number of items in the list Public Function Count() As Integer Return SizeOfList End Function ' Default Constructor: Used to initialize an object Public Sub ListOfParts() ' When this class is primarily accessed, we want to indicate that ' its list is empty SizeOfList = 0 End Sub End Class |
Imports System Module Exercise ' This method is used to request a part number from the user ' Check if that part number exists in the database ' If it does, the method adds that part to the list Private Sub ProcessAnItem(ByVal lc As ListCreator) Dim AnItem As Part Dim PartID As String Dim Qty As Integer ' Ask the user to enter a part number Do Console.Write("Enter the part number (q to stop): ") PartID = Console.ReadLine() ' Scan the list For i As Integer = 0 To PartsList.Description.Length - 1 AnItem = New Part ' If the part number exists in our database If PartID = PartsList.ItemNumber(i) Then ' Create a Part object from it AnItem.PartNumber = PartsList.ItemNumber(i) AnItem.PartName = PartsList.Description(i) AnItem.UnitPrice = PartsList.Price(i) ' Request the quantity from the user Try Console.Write("How many? ") Qty = CInt(Console.ReadLine()) AnItem.Quantity = Qty Catch ex As InvalidCastException Console.WriteLine("Invalid Quantity!!!") End Try ' Once the part has been "built", add it to the order lc.Add(AnItem) End If Next Loop While PartID <> "q" And PartID <> "Q" End Sub ' This method is used to display a receipt ' It uses a list, Receipt, passed as argument ' It also calculates the price of each item and the total price of the order ' They are also part of the receipt Private Sub DisplayReceipt(ByVal Receipt As ListCreator) Dim SubTotal As Double, TotalOrder As Double Console.WriteLine("========================================================") Console.WriteLine(" =-= Four-Corner Auto-Parts =-=") Console.WriteLine("------+---+-------------------------+-------+-----------") Console.WriteLine("Part# Qty Description Price SubTotal") Console.WriteLine("------+---+-------------------------+-------+-----------") For i As Integer = 0 To Receipt.Count() - 1 'TPart Item = Receipt.Retrieve(i) SubTotal = Receipt.Retrieve(i).UnitPrice * Receipt.Retrieve(i).Quantity() TotalOrder += SubTotal Console.WriteLine("{0} {1} {2} {3,6} {4,6}", _ Receipt.Retrieve(i).PartNumber, _ Receipt.Retrieve(i).Quantity, _ Receipt.Retrieve(i).PartName, _ Receipt.Retrieve(i).UnitPrice, _ SubTotal) Next Console.WriteLine("------+---+-------------------------+-------+-----------") Console.WriteLine("Total Order: {0:C}", TotalOrder) Console.WriteLine("========================================================") End Sub Public Sub main() Dim lstParts As ListCreator = New ListCreator ProcessAnItem(lstParts) Console.WriteLine() DisplayReceipt(lstParts) Console.WriteLine() End Sub End Module |
Enter the part number (q to stop): LA943 How many? 1 Enter the part number (q to stop): TR944 How many? 2 Enter the part number (q to stop): EQ173 How many? 1 Enter the part number (q to stop): QT847 How many? 1 Enter the part number (q to stop): q ======================================================== =-= Four-Corner Auto-Parts =-= ------+---+-------------------------+-------+----------- Part# Qty Description Price SubTotal ------+---+-------------------------+-------+----------- LA943 1 Clutch Master Clndr 124.55 124.55 TR944 2 Front Wheel Lug Nut 1.75 3.50 EQ173 1 Oil Pump 155.75 155.75 QT847 1 Water Pump 12.95 12.95 ------+---+-------------------------+-------+----------- Total Order: $296.75 ======================================================== |
A Class Array Passed as Argument |
Like a regular data type, a class can be passed to a procedure as argument. Everything is primarily done the same except that, since the argument is an array, each member of the array is a variable in its own right, with a value for each member variable of the class. Based on this, when dealing with the argument, you can access each of its members individually using its index. |
Returning a Class Array From a Method |
Once again, like a regular variable, an array can be returned from a function. The syntax also follows that of a regular data type. When the function ends, you must make sure it returns an array and not a regular variable. |
|
||
Previous | Copyright © 2005-2016, FunctionX | |
|