Download presentation
Presentation is loading. Please wait.
1
Chapter 23 – Data Structures and Collections
Outline 23.1 Introduction 23.2 Self-Referential Classes 23.3 Linked Lists 23.4 Stacks 23.5 Queues 23.6 Trees Binary Search Tree of Integer Values Binary Search Tree of IComparable Objects 23.7 Collection Classes Class Array Class ArrayList Class Stack Class Hashtable
2
Dynamic Data Structures
23.1 Introduction Dynamic Data Structures Can grow and shrink at execution time: Linked Lists Stacks Queues Binary trees Classes, Inheritance, and Composition help to create and package the data structures to enhance reusability and maintainability
3
23.2 Self-Referential Classes
Contains a reference member referring to a class object of the same class type Self-Referential Object Usually referred to as a link, because it can be used to “tie” together an object of the same type Can be linked together to form useful data structures Nothing reference Usually defines the end of a data structure
4
23.2 Self-Referential Classes
Dynamic Memory Allocation The ability of a program to obtain additional memory, to hold new variables Also releases unneeded memory at execution time Visual Basic performs automatic garbage collection Keyword New Essential to dynamic memory allocation Dynamically allocates memory for a new object
5
Private instance variables mData and mNextNode
1 ' Fig : Node.vb 2 ' Self-referential Node class. 3 4 Class CNode Private mData As Integer Private mNextNode As CNode 7 Public Sub New(ByVal dataValue As Integer) ' constructor body End Sub ' New 11 ' Property Data Public Property Data() As Integer 14 Get ' get body End Get 18 Set(ByVal dataValue As Integer) ' set body End Set 22 End Property ' Data 24 ' Property NextNode Public Property NextNode As CNode 27 Get ' get next node End Get 31 Set(ByVal nodeValue As CNode) ' set next node End Set 35 23.2 Self-Referential Classes Private instance variables mData and mNextNode Node.vb Define CNode constructor Cnode property for mData Cnode property for mNextNode Property for mData, named Data Property for mNextNode, named NextNode
6
36 End Property ' NextNode 37 38 End Class 'CNode
Node.vb
7
23.3 Linked Lists Nodes A linked list is a linear collection of self-referential class objects, called nodes Nodes are connected by reference links A linked list is accessed via a reference to the first node Each other node is referenced by the current node’s link reference The link reference of the last node is set to Nothing A node can contain data of any type Data is stored in a linked list dynamically
8
Advantages of linked lists
Appropriate to use a linked list when the number of elements in the data structure are unknown Linked lists become full only when the system has insufficient memory to satisfy dynamic storage allocation requests A linked list can be maintained in sorted order very easily
9
23.3 Linked Lists 15 10 Fig Self-referential class objects linked together. H D …… Q firstNode lastNode Fig Linked-list graphical representation.
10
1 ' Fig : ListNodes.vb 2 ' Class to represent one node in a CList. 3 4 Public Class CListNode Private mData As Object Private mNextNode As CListNode 7 ' create CListNode with dataValue in list Public Sub New(ByVal dataValue As Object) MyClass.New(dataValue, Nothing) End Sub ' New 12 ' create CListNode with dataValue and nextNodeValue in list Public Sub New(ByVal dataValue As Object, _ ByVal nextNodeValue As Object) 16 mData = dataValue mNextNode = nextNodeValue End Sub ' New 20 ' property Data Public ReadOnly Property Data() As Object 23 Get Return mData End Get 27 End Property ' Data 29 ' property mNext Public Property NextNode() As CListNode 32 Get Return mNextNode End Get ListNodes.vb Define CListNode constructor that takes one argument constructor that takes two arguments Data property NextNode property A Clist accesses the CListNode member variables via it’s properties Data, And NextNode
11
ListNodes.vb 36 37 Set(ByVal value As CListNode) 38 mNextNode = value
End Set 40 End Property ' NextNode 42 43 End Class ' CListNode ListNodes.vb
12
The constructors for Clist initialize both references to Nothing
1 ' Fig : List.vb 2 ' Class CList definition. 3 4 Public Class CList Private firstNode As CListNode Private lastNode As CListNode Private name As String 8 ' construct empty List with specified name Public Sub New(ByVal listName As String) name = listName firstNode = Nothing lastNode = Nothing End Sub ' New 15 ' construct empty List with "list" as its name Public Sub New() MyClass.New("list") End Sub ' New 20 ' insert object at front of List Public Sub InsertAtFront(ByVal insertItem As Object) 23 SyncLock (Me) ' ensure thread safe 25 ' if this list is empty, create node If IsEmpty() Then lastNode = New CListNode(insertItem) firstNode = lastNode Else ' create node and insert before first node firstNode = New CListNode(insertItem, firstNode) End If 33 End SyncLock 35 Private member variable firstNode, a reference to the first CListNode in a CList The constructors for Clist initialize both references to Nothing List.vb Define CList constructor constructor which sets the name member variable method InsertAtFront Private member variable lastNode, a reference to the last CListNode in a CList Methods InsertAtFront, InsertAtBack, RemoveFromFront, and RemoveFromBack, are the primary methods of the CList Method InsertAtFront places a new node at the front of the list Call IsEmpty to determine whether the list is empty Each method uses a SyncLock block to ensure that Clist objects are multithread safe when used in a multithread program
13
List.vb method InsertAtBack method RemoveFromFront
If the list is empty, set both firstNode and lastNode to refer to a new CListNode initialized with object insertItem End Sub ' InsertAtFront 37 ' insert object at end of List Public Sub InsertAtBack(ByVal insertItem As Object) 40 SyncLock (Me) ' ensure thread safety 42 ' if list is empty create node and set firstNode If IsEmpty() Then lastNode = New CListNode(insertItem) firstNode = lastNode Else ' create node and insert after last node lastNode.NextNode = New CListNode(insertItem) lastNode = lastNode.NextNode End If 51 End SyncLock 53 End Sub ' InsertAtBack 55 ' remove first node from list Public Function RemoveFromFront() As Object 58 SyncLock (Me) ' ensure thread safety Dim removeItem As Object = Nothing 61 ' throw exception if removing node from empty list If IsEmpty() Then Throw New EmptyListException(name) End If 66 removeItem = firstNode.Data ' retrieve data 68 List.vb method InsertAtBack method RemoveFromFront Method InsertAtBack places a new node at the back of the list If the list is not empty, thread the new node into the list by setting lastNode and lastNode.NextNode to refer to a new CListNode object initialized with object insertItem Method RemoveFromFront removes the front node of the list and returns a reference to the removed data. The method throws a EmptyListException if the program tries to remove a node from an empty list
14
List.vb method RemoveFromBack
' reset firstNode and lastNode references If firstNode Is lastNode Then firstNode = Nothing lastNode = Nothing Else firstNode = firstNode.NextNode End If 76 Return removeItem ' return removed item 78 End SyncLock 80 End Function ' RemoveFromFront 82 ' remove last node from CList Public Function RemoveFromBack() As Object 85 SyncLock (Me) ' ensure thread safe Dim removeItem As Object = Nothing 88 ' throw exception if removing node from empty list If IsEmpty() Then Throw New EmptyListException(name) End If 93 removeItem = lastNode.Data ' retrieve data 95 ' reset firstNode and last node references If firstNode Is lastNode Then lastNode = Nothing firstNode = lastNode Else Dim current As CListNode = firstNode 102 Method RemoveFromBack removes the last node of the list and returns a reference to the removed data. The method throws a EmptyListException if the program tries to remove a node from an empty list List.vb method RemoveFromBack
15
List.vb method IsEmpty Print
' loop while current node is not lastNode While (Not (current.NextNode Is lastNode)) current = current.NextNode ' move to next node End While 107 ' current is new lastNode lastNode = current current.NextNode = Nothing End If 112 Return removeItem ' return removed data 114 End SyncLock 116 End Function ' RemoveFromBack 118 ' return true if list is empty Public Function IsEmpty() As Boolean 121 SyncLock (Me) 123 If firstNode Is Nothing Then Return True Else Return False End If 129 End SyncLock 131 End Function ' IsEmpty 133 ' output List contents Public Overridable Sub Print() 136 List.vb method IsEmpty Print Method IsEmpty is a predicate method that determines whether the list is empty, i.e. whether the reference to the first node of the list is empty
16
SyncLock (Me) 138 If IsEmpty() Then Console.WriteLine("Empty " & name) 141 Return End If 144 Console.Write("The " & name & " is: ") 146 Dim current As CListNode = firstNode 148 ' output current node data while not at end of list While Not current Is Nothing Console.Write(current.Data & " ") current = current.NextNode End While 154 Console.WriteLine(vbCrLf) 156 End SyncLock 158 End Sub ' Print 160 161 End Class ' CList Creates CListNode reference current and initializes it with firstnode. While current is not Nothing, there are still items in the list, so the method prints current.Data and then assigns current.NextNode to current List.vb writes to console window writes data from current node to console Method Print first determines whether the list is empty, if so Print displays a String consisting of “Empty” and the list’s name and then returns control to the calling method. Otherwise, Print outputs the data in the list.
17
EmptyListException.vb Define EmptyListException constructor
1 ' Fig : EmptyListException.vb 2 ' Class EmptyListException definition. 3 4 Public Class EmptyListException Inherits ApplicationException 6 Public Sub New(ByVal name As String) MyBase.New("The " & name & " is empty") End Sub ' New 10 11 End Class ' EmptyListException EmptyListException.vb Define EmptyListException constructor
18
ListTest.vb Define modListTest main
1 ' Fig : ListTest.vb 2 ' Testing class CList. 3 4 ' Deitel namespaces 5 Imports LinkedListLibrary 6 7 Module modListTest 8 Sub Main() Dim list As CList = New CList() ' create CList container 11 ' create data to store in CList Dim aBoolean As Boolean = True Dim aCharacter As Char = "$"c Dim anInteger As Integer = 34567 Dim aString As String = "hello" 17 ' use CList insert methods list.InsertAtFront(aBoolean) ' insert Boolean at front list.Print() 21 list.InsertAtFront(aCharacter) ' insert Char at front list.Print() 24 list.InsertAtBack(anInteger) ' insert Integer at back list.Print() 27 list.InsertAtBack(aString) ' insert String at back list.Print() 30 ' use CList remove methods Dim removedObject As Object 33 ' remove data from list and print after each removal Try ListTest.vb Define modListTest main
19
ListTest.vb 36 37 ' remove object from front of list
removedObject = list.RemoveFromFront() Console.WriteLine(Convert.ToString(removedObject) & _ " removed") 41 list.Print() 43 ' remove object from front of list removedObject = list.RemoveFromFront() Console.WriteLine(Convert.ToString(removedObject) & _ " removed") 48 list.Print() 50 ' remove object from back of list removedObject = list.RemoveFromBack() Console.WriteLine(Convert.ToString(removedObject) & _ " removed") 55 list.Print() 57 ' remove object from back of list removedObject = list.RemoveFromBack() Console.WriteLine(Convert.ToString(removedObject) & _ " removed") 62 list.Print() 64 ' Catch exception if list is empty Catch emptyListException As EmptyListException Console.Error.WriteLine(vbCrLf & _ Convert.ToString(emptyListException)) 69 End Try ListTest.vb
20
71 72 End Sub ' Main 73 74 End Module ' modListTest
ListTest.vb The list is: True The list is: $ True The list is: $ True 34567 The list is: $ True hello $ removed The list is: True hello True removed The list is: hello hello removed The list is: 34567 34567 removed Empty list
21
23.3 Linked Lists 11 7 12 new ListNode (a) firstNode (b) Fig InsertAtFront graphical representation.
22
23.3 Linked Lists (a) 7 12 New ListNode 11 5 firstNode lastNode (b) Fig InsertAtBack graphical representation.
23
23.3 Linked Lists (a) 7 12 lastNode 11 5 firstNode (b) removeItem Fig RemoveFromFront graphical representation.
24
23.3 Linked Lists (a) 7 12 lastNode 11 5 firstNode (b) current removeItem Fig RemoveFromBack graphical representation.
25
23.4 Stacks Stack New nodes can be added and removed only at the top Last-in, first-out (LIFO) data structure Bottom of stack indicated by the link member in the bottom node of the stack set to Nothing Constrained version of a linked list Push Adds a new node to the top of the stack Pop Removes a node from the top of the stack Returns the data from the popped node
26
Class CstackInheritance inherits from class CList
1 ' Fig: 23.12: StackInheritance.vb 2 ' Implementing a stack by inheriting from class CList. 3 4 ' Deitel namespaces 5 Imports LinkedListLibrary 6 7 ' class CStackInheritance inherits class CList 8 Public Class CStackInheritance Inherits CList 10 ' pass name "stack" to CList constructor Public Sub New() MyBase.New("stack") End Sub ' New 15 ' place dataValue at top of stack by inserting dataValue at ' front of linked list Public Sub Push(ByVal dataValue As Object) MyBase.InsertAtFront(dataValue) End Sub ' Push 21 ' remove item from top of stack by removing item at front of ' linked list Public Function Pop() As Object Return MyBase.RemoveFromFront() End Function ' Pop 27 28 End Class ' CStackInheritance Class CstackInheritance inherits from class CList StackInheritance.vb inherits from class Clist constructor Push method Pop method Method Push calls InsertAtFront Method Pop calls RemoveFromFront
27
StackTest.vb main objects to Push on the stack
1 ' Fig : StackTest.vb 2 ' Testing stack implementations. 3 4 ' Deitel namespaces 5 Imports LinkedListLibrary 6 Imports StackInheritanceLibrary 7 8 ' demonstrates functionality of stack implementations 9 Module modStackInheritanceTest 10 Sub Main() Dim stack As CStackInheritance = New CStackInheritance() 13 ' create objects to store in stack Dim aBoolean As Boolean = True Dim aCharacter As Char = Convert.ToChar("$") Dim anInteger As Integer = 34567 Dim aString As String = "hello" 19 ' use method Push to add items to stack stack.Push(aBoolean) ' add Boolean stack.Print() 23 stack.Push(aCharacter) ' add Char stack.Print() 26 stack.Push(anInteger) ' add Integer stack.Print() 29 stack.Push(aString) ' add String stack.Print() 32 ' use method Pop to remove items from stack Dim removedObject As Object = Nothing 35 Defines four objects that will be pushed onto the stack and popped off the stack StackTest.vb main objects to Push on the stack These lines push the objects onto the stack
28
StackTest.vb Pop the objects off the stack
' remove items from stack Try 38 ' pop item and output removed item While True removedObject = stack.Pop() Console.WriteLine(removedObject & " popped") stack.Print() End While 45 ' catch exception if Pop was called while stack empty Catch emptyListException As EmptyListException Console.Error.WriteLine(emptyListException.StackTrace) End Try 50 End Sub ' Main 52 53 End Module ' modStackTest StackTest.vb Pop the objects off the stack An infinite While loop pops the elements from the stack. The program uses method Print, inherited from class Clist, to output the contents of the stack after each operation. The stack is: True The stack is: $ True The stack is: $ True The stack is: hello $ True hello popped 34567 popped
29
StackTest.vb $ popped The stack is: True True popped Empty stack
True popped Empty stack at LinkedListLibrary.CList.RemoveFromFront() in C:\books\2001\vbhtp2\ch23\Examples\Fig23_04\LinkedListLibrary\List.vb:line 64 at StackInheritanceLibrary.CStackInheritance.Pop() in C:\books\2001\vbhtp2\ch23\Examples\Fig23_12\StackInheritanceLibrary\StackInheritance.vb:line 25 at StackInheritanceTest.modStackInheritance.Main() in C:\books\2001\vbhtp2\ch23\Examples\Fig23_13\StackTest\StackTest.vb:line 41 StackTest.vb
30
StackComposition.vb constructor Push method Pop method IsEmpty Print
1 ' Fig : StackComposition.vb 2 ' StackComposition definition with composed CList object. 3 4 ' Deitel namespaces 5 Imports LinkedListLibrary 6 7 ' class CStackComposition encapsulates CList's capabilities 8 Public Class CStackComposition Private stack As CList 10 ' construct empty stack Public Sub New() stack = New CList("stack") End Sub ' New 15 ' add object to stack Public Sub Push(ByVal dataValue As Object) stack.InsertAtFront(dataValue) End Sub ' Push 20 ' remove object from stack Public Function Pop() As Object Return stack.RemoveFromFront() End Function ' Pop 25 ' determine whether stack is empty Public Function IsEmpty() As Boolean Return stack.IsEmpty() End Function ' IsEmpty 30 ' output stack content Public Sub Print() stack.Print() End Sub ' Print Composition enables us to hide the methods of class Clist that should not appear in our Stack’s Public interface by providing Public interface methods only to the required Clist methods StackComposition.vb constructor Push method Pop method IsEmpty Print
31
35 36 End Class ' CStackComposition
StackComposition.vb
32
23.5 Queues Queue Similar to a supermarket checkout line
First-in, first-out (FIFO) data structure Nodes are removed only from the head Nodes are inserted only at the tail The insert and remove operations are known as enqueue and dequeue Useful in computing Print spooling, information packets in networks, file server requests
33
Inherits the Clist class
1 ' Fig : QueueInheritance.vb 2 ' Implementing a queue by inheriting from class CList. 3 4 ' Deitel namespaces 5 Imports LinkedListLibrary 6 7 ' class CQueueInheritance inherits from class CList 8 Public Class CQueueInheritance Inherits CList 10 ' pass name "queue" to CList constructor Public Sub New() MyBase.New("queue") End Sub 15 ' place dataValue at end of queue by inserting dataValue at end ' of linked list Public Sub Enqueue(ByVal dataValue As Object) MyBase.InsertAtBack(dataValue) End Sub ' Enqueue 21 ' remove item from front of queue by removing item at front of ' linked list Public Function Dequeue() As Object Return MyBase.RemoveFromFront() End Function ' Dequeue 27 28 End Class ' CQueueInheritance Inherits the Clist class QueueInheritance.vb inherits from Clist constructor method Enqueue method Dequeue Method Enqueue calls the InsertAtBack method of it’s base-class Method Dequeue calls the RemoveFromFront method of it’s base-class
34
Objects are created and then added to the queue
1 ' Fig : QueueTest.vb 2 ' Testing queue implementation. 3 4 ' Deitel namespaces 5 Imports LinkedListLibrary 6 Imports QueueInheritanceLibrary 7 8 ' demonstrate queue functionality 9 Module modQueueTest 10 Sub Main() Dim queue As CQueueInheritance = New CQueueInheritance() 13 ' create data to store in queue Dim aBoolean As Boolean = True Dim aCharacter As Char = Convert.ToChar("$") Dim anInteger As Integer = 34567 Dim aString As String = "hello" 19 ' use method Enqueue to add items to queue queue.Enqueue(aBoolean) ' add Boolean queue.Print() 23 queue.Enqueue(aCharacter) ' add Char queue.Print() 26 queue.Enqueue(anInteger) ' add Integer queue.Print() 29 queue.Enqueue(aString) ' add String queue.Print() 32 ' use method Dequeue to remove items from queue Dim removedObject As Object = Nothing 35 QueueTest.vb main objects to be added to the queue insert the objects to the queue Objects are created and then added to the queue
35
QueueTest.vb removing the objects from the queue
' remove items from queue Try 38 ' dequeue item and output removed item While True removedObject = queue.Dequeue() Console.WriteLine(removedObject & " dequeue") queue.Print() End While 45 ' if exception occurs, print stack trace Catch emptyListException As EmptyListException Console.Error.WriteLine(emptyListException.StackTrace) End Try 50 End Sub ' Main 52 53 End Module ' modQueueTest QueueTest.vb removing the objects from the queue An infinite While loop dequeues the elements from the queue until no objects are left The queue is: True The queue is: True $ The queue is: True $ 34567 The queue is: True $ hello True dequeue The queue is: $ hello $ dequeue The queue is: hello
36
QueueTest.vb 34567 dequeue The queue is: hello hello dequeue
hello dequeue Empty queue at LinkedListLibrary.CList.RemoveFromFront() in C:\books\2001\vbhtp2\ch23\Examples\Fig23_04\LinkedListLibrary\List.vb:line 64 at QueueInheritanceLibrary.CQueueInheritance.Dequeue() in C:\books\2001\vbhtp2\ch23\Examples\Fig23_15\QueueInheritanceLibrary\QueueInheritance.vb:line 25 at QueueTest.modQueueInheritanceTest.Main() in C:\books\2001\vbhtp2\ch23\Examples\Fig23_16\QueueTest\QueueTest.vb: line 41 QueueTest.vb
37
23.6 Trees Tree Binary trees
A nonlinear, two-dimensional data structure nodes contain two or more links all other data structures we have discussed only contain one Binary trees all nodes contain two links none, one, or both of which may be Nothing The root node is the first node in a tree. Each link in the root node refers to a child The left child is the first node in the left subtree, and the right child is the first node in the right subtree A node with no children is called a leaf node
38
23.6 Trees B A D C Fig Binary tree graphical representation.
39
23.6 Trees 47 25 77 11 7 17 65 93 68 43 31 44 Fig A binary search tree containing 12 values.
40
Class CTreeNode is a self-referential class containing three Private data members. Two of type CTreeNode, mLeftNode and mRightNode, and one of type Integer, mData 1 ' Fig : TreeNode.vb 2 ' Class CTreeNode represents a node in a CTree. 3 4 Public Class CTreeNode Private mLeftNode As CTreeNode Private mData As Integer Private mRightNode As CTreeNode 8 ' initialize data and make that a leaf node Public Sub New(ByVal nodeData As Integer) mData = nodeData mRightNode = Nothing ' node has no children LeftNode = Nothing ' node has no children End Sub ' New 15 ' property LeftNode Public Property LeftNode() As CTreeNode 18 Get Return mLeftNode End Get 22 Set(ByVal value As CTreeNode) mLeftNode = value End Set 26 End Property ' LeftNode 28 ' property Data Public Property Data() As Integer 31 Get Return mData End Get 35 Constructor initializes references mLeftNode and mRightNode to Nothing, initially making every CTreeNode a leaf node TreeNode.vb Private member variables of CTreeNode constructor Property LeftNode Property Data Properties LeftNode, Data, and RightNode provide access to a CTreeNode’s Private data members.
41
TreeNode.vb Property RightNode method Insert
Set(ByVal value As Integer) mData = value End Set 39 End Property ' Data 41 ' property RightNode Public Property RightNode() As CTreeNode 44 Get Return mRightNode End Get 48 Set(ByVal value As CTreeNode) mRightNode = value End Set 52 End Property ' RightNode 54 ' insert node into tree Public Sub Insert(ByVal insertValue As Integer) 57 ' insert in left subtree If insertValue < mData Then 60 ' insert new CTreeNode If mLeftNode Is Nothing Then LeftNode = New CTreeNode(insertValue) 64 ' continue traversing left subtree Else LeftNode.Insert(insertValue) End If 69 TreeNode.vb Property RightNode method Insert Method Insert recursively determines the location for the new node in the tree and inserts the node at that location. It compares the value to insert with the mData value in the root node. Then it determines whether it should be inserted in the left subtree or the right subtree depending on it’s value compared to the other nodes in the tree.
42
TreeNode.vb 70 ' insert in right subtree
ElseIf insertValue > mData Then 72 ' insert new CTreeNode If RightNode Is Nothing Then RightNode = New CTreeNode(insertValue) 76 ' continue traversing right subtree Else RightNode.Insert(insertValue) End If 81 End If 83 End Sub ' Insert 85 86 End Class ' CTreeNode TreeNode.vb
43
Tree.vb constructor InsertNode method PreorderTraversal method
Class CTree manipulates objects of class CTreeNode. It contains a Private root node, a reference to the root node of the tree. 1 ' Fig : Tree.vb 2 ' Class CTree is a tree containing CTreeNodes. 3 4 Public Class CTree Private root As CTreeNode 6 ' construct an empty CTree of integers Public Sub New() root = Nothing End Sub ' New 11 ' insert new node in binary search tree Public Sub InsertNode(ByVal insertValue As Integer) 14 SyncLock (Me) 16 ' if node does not exist, create node If root Is Nothing Then root = New CTreeNode(insertValue) Else ' otherwise insert node into tree root.Insert(insertValue) End If 23 End SyncLock 25 End Sub ' InsertNode 27 ' begin preorder traversal Public Sub PreorderTraversal() 30 SyncLock (Me) PreorderHelper(root) End SyncLock 34 End Sub ' PreOrderTraversal Tree.vb constructor InsertNode method PreorderTraversal method The CTree constructor initializes root to Nothing to indicate that the tree is initially empty Method InsertNode inserts a node in the tree. It calls CTreeNode method Insert. Methods InorderTraversal, PreorderTraversal and PostorderTraversal call helper methods InorderHelper, PreorderHelper and PostorderHelper, respectively, to traverse the tree and print the node values The PreorderTraversal method processes the value in each node as the node is visited. After it processes the values in the left subtree, then the values in the right subtree.
44
36 ' recursive method to perform preorder traversal Private Sub PreorderHelper(ByVal node As CTreeNode) 39 If node Is Nothing Then Return End If 43 ' output node data Console.Write(node.Data & " ") 46 ' traverse left subtree PreorderHelper(node.LeftNode) 49 ' traverse right subtree PreorderHelper(node.RightNode) 52 End Sub ' PreorderHelper 54 ' begin inorder traversal Public Sub InorderTraversal() 57 SyncLock (Me) InorderHelper(root) End SyncLock 61 End Sub ' InorderTraversal 63 ' recursive method to perform inorder traversal Private Sub InorderHelper(ByVal node As CTreeNode) 66 If node Is Nothing Then Return End If 70 Tree.vb helper method PreorderHelper method InorderTraversal helper method InorderHelper The helper methods in class CTree allow the programmer to start the traversal without first obtaining a reference to the root node first. Methods InorderTraversal, PreorderTraversal and PostorderTraversal simply take the Private reference root and pass it to the appropriate helper method to initiate the traversal of the tree The InorderTraversal method does not process the value in a node until the values in that node’s left subtree are processed
45
Tree.vb method PostorderTraversal helper method PostorderHelper
' traverse left subtree InorderHelper(node.LeftNode) 73 ' output node data Console.Write(node.Data & " ") 76 ' traverse right subtree InorderHelper(node.RightNode) 79 End Sub ' InorderHelper 81 ' begin postorder traversal Public Sub PostorderTraversal() 84 SyncLock (Me) PostorderHelper(root) End SyncLock 88 End Sub ' PostorderTraversal 90 ' recursive method to perform postorder traversal Private Sub PostorderHelper(ByVal node As CTreeNode) 93 If node Is Nothing Then Return End If 97 ' traverse left subtree PostorderHelper(node.LeftNode) 100 ' traverse right subtree PostorderHelper(node.RightNode) 103 The PostorderTraversal method processes the value in each node after the values of all that node’s children are processed Tree.vb method PostorderTraversal helper method PostorderHelper
46
Tree.vb 104 ' output node data 105 Console.Write(node.Data & " ") 106
End Sub ' PostorderHelper 108 109 End Class ' CTree Tree.vb
47
TreeTest.vb 1 ' Fig. 23.21: TreeTest.vb
2 ' This program tests class CTree. 3 4 ' Deitel namespaces 5 Imports BinaryTreeLibrary 6 7 Module modTreeTest 8 ' test class CTree Sub Main() Dim tree As CTree = New CTree() Dim insertValue As Integer Dim i As Integer 14 Console.WriteLine("Inserting Values: ") Dim randomNumber As Random = New Random() 17 ' insert 10 random integers from 0-99 in tree For i = 1 To 10 insertValue = randomNumber.Next(100) Console.Write(insertValue & " ") tree.InsertNode(insertValue) Next 24 ' perform preorder traversal of tree Console.WriteLine(vbCrLf & vbCrLf & "Preorder Traversal") tree.PreOrderTraversal() 28 ' perform inorder traversal of tree Console.WriteLine(vbCrLf & vbCrLf & "Inorder Traversal") tree.InOrderTraversal() 32 TreeTest.vb
48
TreeTest.vb 33 ' perform postorder traversal of tree
Console.WriteLine(vbCrLf & vbCrLf & "Postorder Traversal") tree.PostOrderTraversal() 36 Console.WriteLine() End Sub ' Main 39 40 End Module ' modTreeTest TreeTest.vb Inserting Values: Preorder Traversal Inorder Traversal Postorder Traversal
49
23.6 Trees 27 13 42 6 33 48 17 Fig A binary search tree.
50
Here we take advantage of Visual Basic’s polymorphic capabilities and we implement classes CTreeNode and CTree, which now manipulates objects that implement the interface IComparable 1 ' Fig : TreeNode2.vb 2 ' Class CTreeNode uses IComparable objects for objects 3 4 Public Class CTreeNode Private mLeftNode As CTreeNode Private mData As IComparable Private mRightNode As CTreeNode 8 ' initialize data and make this a leaf node Public Sub New(ByVal nodeData As IComparable) mData = nodeData mRightNode = Nothing ' node has no children LeftNode = Nothing ' node has no children End Sub ' New 15 ' property LeftNode Public Property LeftNode() As CTreeNode 18 Get Return mLeftNode End Get 22 Set(ByVal value As CTreeNode) mLeftNode = value End Set 26 End Property ' LeftNode 28 ' property Data Public Property Data() As IComparable 31 Get Return mData End Get 35 TreeNode2.vb Private member variables constructor Property LeftNode Property Data Instead of being a binary search tree of type Integer, it is now of type IComparable data
51
36 Set(ByVal value As IComparable)
mData = value End Set 39 End Property ' Data 41 ' property RightNode Public Property RightNode() As CTreeNode 44 Get Return mRightNode End Get 48 Set(ByVal value As CTreeNode) mRightNode = value End Set 52 End Property ' RightNode 54 ' insert node into tree Public Sub Insert(ByVal insertValue As IComparable) 57 'insert in left subtree If insertValue.CompareTo(mData) < 0 Then 60 ' insert new TreeNode If mLeftNode Is Nothing Then LeftNode = New CTreeNode(insertValue) 64 ' continue traversing left subtree Else LeftNode.Insert(insertValue) End If 69 Instead of being a binary search tree of type Integer, it is now of type IComparable data TreeNode2.vb Property RightNode Insert Method call to the Interfaces CompareTo method This line now compares Icomparable objects using the interfaces method CompareTo
52
TreeNode2.vb 70 ' insert in right subtree
ElseIf insertValue.CompareTo(mData) Then 72 ' insert new TreeNode If RightNode Is Nothing Then RightNode = New CTreeNode(insertValue) 76 ' continue traversing right subtree Else RightNode.Insert(insertValue) End If 81 End If 83 End Sub ' Insert 85 86 End Class ' CTreeNode TreeNode2.vb
53
1 ' Fig : Tree2.vb 2 ' Class CTree contains nodes with IComparable data 3 4 Public Class CTree Private root As CTreeNode 6 ' construct an empty CTree of integers Public Sub New() root = Nothing End Sub ' New 11 ' insert new node in binary search tree Public Sub InsertNode(ByVal insertValue As IComparable) 14 SyncLock (Me) 16 ' if node does not exist, create one If root Is Nothing Then root = New CTreeNode(insertValue) Else ' otherwise insert node in tree root.Insert(insertValue) End If 23 End SyncLock 25 End Sub ' InsertNode 27 ' begin preorder traversal Public Sub PreorderTraversal() 30 SyncLock (Me) PreorderHelper(root) End SyncLock 34 End Sub ' PreorderTraversal Tree2.vb constructor method InsertNode calls the Insert method of class CTreeNode method PreorderTraversal Instead of being a binary search tree of type Integer, it is now of type IComparable data
54
36 ' recursive method to perform preorder traversal Private Sub PreorderHelper(ByVal node As CTreeNode) 39 If node Is Nothing Then Return End If 43 ' output node data Console.Write(Convert.ToString(node.Data) & " ") 46 ' traverse left subtree PreOrderHelper(node.LeftNode) 49 ' traverse right subtree PreOrderHelper(node.RightNode) 52 End Sub ' PreOrderHelper 54 ' begin inorder traversal Public Sub InorderTraversal() 57 SyncLock (Me) InorderHelper(root) End SyncLock 61 End Sub ' InorderTraversal 63 ' recursive method to perform inorder traversal Private Sub InorderHelper(ByVal node As CTreeNode) 66 If node Is Nothing Then Return End If 70 Tree2.vb helper method PreorderHelper method InorderTraversal helper method InorderHelper
55
Tree2.vb method PostorderTraversal helper method PostorderHelper
' traverse left subtree InorderHelper(node.LeftNode) 73 ' output node data Console.Write(Convert.ToString(node.Data) & " ") 76 ' traverse right subtree InorderHelper(node.RightNode) 79 End Sub ' InorderHelper 81 ' begin postorder traversal Public Sub PostorderTraversal() 84 SyncLock (Me) PostOrderHelper(root) End SyncLock 88 End Sub ' PostorderTraversal 90 ' recursive method to perform postorder traversal Private Sub PostorderHelper(ByVal node As CTreeNode) 93 If node Is Nothing Then Return End If 97 ' traverse left subtree PostorderHelper(node.LeftNode) 100 ' traverse right subtree PostorderHelper(node.RightNode) 103 ' output node data Console.Write(Convert.ToString(node.Data) & " ") Tree2.vb method PostorderTraversal helper method PostorderHelper
56
106 107 End Sub ' PostorderHelper 108 109 End Class ' CTree
Tree2.vb
57
TreeTest2.vb main 1 ' Fig. 23.25: TreeTest2.vb
2 ' This program tests class CTree. 3 4 ' Deitel namespaces 5 Imports BinaryTreeLibrary2 6 7 Module modTreeTest2 8 ' test class CTree. Sub Main() Dim integerArray As Integer() = {8, 2, 4, 3, 1, 7, 5, 6} Dim doubleArray As Double() = _ {8.8, 2.2, 4.4, 3.3, 1.1, 7.7, 5.5, 6.6} 14 Dim stringArray As String() = {"eight", "two", "four", _ "three", "one", "seven", "five", "six"} 17 ' create Integer tree Dim integerTree As CTree = New CTree() PopulateTree(integerArray, integerTree, "integerTree") TraverseTree(integerTree, "integerTree") 22 ' create Double tree Dim doubleTree As CTree = New CTree() populateTree(doubleArray, doubleTree, "doubleTree") TraverseTree(doubleTree, "doubleTree") 27 ' create String tree Dim stringTree As CTree = New CTree() populateTree(stringArray, stringTree, "stringTree") TraverseTree(stringTree, "stringTree") 32 End Sub ' Main 34 TreeTest2.vb main
58
TreeTest2.vb 35 ' populate tree with array elements
Public Sub PopulateTree(ByVal array As Array, _ ByVal tree As CTree, ByVal name As String) 38 Dim data As IComparable Console.WriteLine(vbCrLf & "Inserting into " & name & ":") 41 For Each data In array Console.Write(Convert.ToString(data) & " ") tree.InsertNode(data) Next 46 End Sub ' PopulateTree 48 ' perform traversals Public Sub TraverseTree(ByVal tree As CTree, _ ByVal treeType As String) 52 ' perform preorder traversal of tree Console.WriteLine(vbCrLf & vbCrLf & _ "Preorder Traversal of " & treeType) 56 tree.PreorderTraversal() 58 ' perform inorder traversal of tree Console.WriteLine(vbCrLf & vbCrLf & _ "Inorder Traversal of " & treeType) 62 tree.InorderTraversal() 64 ' perform postorder traversal of tree Console.WriteLine(vbCrLf & vbCrLf & _ "Postorder Traversal of " & treeType) 68 TreeTest2.vb
59
TreeTest2.vb 69 tree.PostorderTraversal() 70
Console.WriteLine(vbCrLf) End Sub ' TraverseTree 73 74 End Module ' CTreeTest2 TreeTest2.vb Inserting into integerTree: Preorder Traversal of integerTree Inorder Traversal of integerTree Postorder Traversal of integerTree Inserting into doubleTree: Preorder Traversal of doubleTree Inorder Traversal of doubleTree Postorder Traversal of doubleTree
60
TreeTest2.vb Inserting into stringTree:
eight two four three one seven five six Preorder Traversal of stringTree eight two four five three one seven six Inorder Traversal of stringTree eight five four one seven six three two Postorder Traversal of stringTree five six seven one three four two eight TreeTest2.vb
61
23.7 Collection Classes Collection Classes Store collections of data
Each instance is known as a collection, which is a set of items The programmer uses existing data structures without worrying about how the data structures are implemented They represent a great example of code reuse Allows for quicker coding, excellent performance, maximum execution speed, and minimize memory consumption
62
1 ' Fig : UsingArray.vb 2 ' Using class Array to perform common array manipulations. 3 4 Imports System.Windows.Forms 5 Imports System.Collections 6 7 ' demonstrate algorithms of class Array 8 Public Class CUsingArray Private integerValues As Integer() = {1, 2, 3, 4, 5, 6} Private doubleValues As Double() = _ {8.4, 9.3, 0.2, 7.9, 3.4} 12 Private integerValuesCopy(6) As Integer Private output As String 15 ' build and display program output Public Sub Start() Dim result As Integer 19 output = "Initial Array Values:" & vbCrLf PrintArray() ' output initial array contents 22 ' sort doubleValues Array.Sort(doubleValues) 25 ' copy integerValues into integerValuesCopy Array.Copy(integerValues, integerValuesCopy, _ integerValues.Length) 29 output &= vbCrLf & vbCrLf & _ "Array values after Sort and Copy:" & vbCrLf 32 PrintArray() ' output array contents output &= vbCrLf & vbCrLf 35 UsingArray.vb Private member variables Start method call to Print method call to Sort method call to Copy method Using SharedArray method Copy to copy elements from array integerArray into array intergerArrayCopy
63
UsingArray.vb PrintArray method
' search for value 5 in integerValues result = Array.BinarySearch(integerValues, 5) 38 If result >= 0 Then output &= "5 found at element " & result & _ " in integerValues" Else output &= "5 not found" & " in integerValues" End If 45 output &= vbCrLf 47 ' search for value 8763 in integerValues result = Array.BinarySearch(integerValues, 8763) 50 If result >= 0 Then output &= "8763 found at element " & _ result & " in integerValues" Else output &= "8763 was not found" & " in integerValues" End If 57 MessageBox.Show(output, "Using Class Array", _ MessageBoxButtons.OK, MessageBoxIcon.Information) 60 End Sub ' Start 62 ' append array output to output string Private Sub PrintArray() Dim doubleElement As Double Dim integerElement As Integer 67 output &= "doubleValues: " 69 Invokes SharedArray method BinarySearch to perform binary searches on array integerValues. Method BinarySearch receives sorted array in which to search and the key for which to search UsingArray.vb PrintArray method
64
UsingArray.vb main 70 ' output each element in array doubleValues
For Each doubleElement In doubleValues output &= doubleElement & " " Next 74 output &= vbCrLf & " integerValues: " 76 ' output each element in array integerValues For Each integerElement In integerValues output &= integerElement & " " Next 81 output &= vbCrLf & " integerValuesCopy: " 83 ' output each element in array integerValuesCopy For Each integerElement In integerValuesCopy output &= integerElement & " " Next 88 End Sub ' PrintArray 90 ' main entry point for application Shared Sub Main() Dim application As CUsingArray = New CUsingArray() application.Start() End Sub ' Main 96 97 End Class ' CUsingArray UsingArray.vb main
65
23.7 Collection Classes
66
23.7 Collection Classes Fig ArrayList methods (partial list).
67
Creates an ArrayList with an initial capacity of one element
1 ' Fig : ArrayListTest.vb 2 ' Demonstrating class ArrayList functionality. 3 4 Imports System.Collections 5 Imports System.Text 6 Imports System.Windows.Forms 7 8 Public Class FrmArrayList Inherits Form 10 ' Buttons for invoking ArrayList functionality Friend WithEvents cmdAdd As Button Friend WithEvents cmdRemove As Button Friend WithEvents cmdFirst As Button Friend WithEvents cmdLast As Button Friend WithEvents cmdIsEmpty As Button Friend WithEvents cmdContains As Button Friend WithEvents cmdLocation As Button Friend WithEvents cmdTrim As Button Friend WithEvents cmdStatistics As Button Friend WithEvents cmdDisplay As Button 22 ' TextBox for user input Friend WithEvents txtInput As TextBox Friend WithEvents lblEnter As Label 26 Friend WithEvents txtConsole As TextBox ' TextBox for output 28 ' Visual Studio .NET generated code 30 ' ArrayList for manipulating Strings Private arrayList As ArrayList = New ArrayList(1) 33 FrmArrayList.vb Creates an ArrayList with an initial capacity of one element
68
34 ' add item to end of arrayList
Private Sub cmdAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdAdd.Click 37 arrayList.Add(txtInput.Text) txtConsole.Text = "Added to end: " & txtInput.Text txtInput.Clear() End Sub ' cmdAdd_Click 42 'remove specified item from arrayList Private Sub cmdRemove_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdRemove.Click 46 arrayList.Remove(txtInput.Text) txtConsole.Text = "Removed: " & txtInput.Text txtInput.Clear() End Sub ' cmdRemove_Click 51 ' display first element Private Sub cmdFirst_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdFirst.Click 55 ' get first element Try txtConsole.Text = "First element: " & arrayList(0) 59 ' show exception if no elements in arrayList Catch outOfRange As ArgumentOutOfRangeException txtConsole.Text = outOfRange.ToString() End Try 64 End Sub ' cmdFirst_Click 66 When the user clicks Add, event handler cmdAdd_Click invokes method Add to append the String in the inputTextBox to the ArrayList FrmArrayList.vb When the user clicks Remove, event handler cmdRemove_Click invokes Remove to remove the String specified in the inputTextBox from the ArrayList Event handlers cmdFirst_Click and cmdLast_Click use the ArrayList subscript operator to retrieve the first element and last element respectively.
69
' display last element Private Sub cmdLast_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdLast.Click 70 ' get last element Try txtConsole.Text = "Last element: " & _ arrayList(arrayList.Count - 1) 75 ' show exception if no elements in arrayList Catch outOfRange As ArgumentOutOfRangeException txtConsole.Text = outOfRange.ToString() End Try 80 End Sub ' cmdLast_Click 82 ' determine whether arrayList is empty Private Sub cmdIsEmpty_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdIsEmpty.Click 86 If arrayList.Count = 0 Then txtConsole.Text = "arrayList is empty" Else txtConsole.Text = "arrayList is not empty" End If 92 End Sub ' cmdIsEmpty_Click 94 ' determine whether arrayList contains specified object Private Sub cmdContains_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdContains.Click 98 If arrayList.Contains(txtInput.Text) Then txtConsole.Text = "arrayList contains " & _ txtInput.Text() FrmArrayList.vb Event handler cmdIsEmpty_Click uses ArrayList property Count to determine whether the ArrayList is empty Event handler cmdContains_Click uses ArrayList method Contains to determine whether the object that Contains receives as an argument currently is in the ArrayList
70
When the user clicks Location, event handler cmdIsEmpty_Click invokes ArrayList method IndexOf to determine the index of a particular object in the ArrayList Else txtConsole.Text = txtInput.Text & " not found" End If 105 End Sub ' cmdContains_Click 107 ' determine location of specified object Private Sub cmdLocation_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdLocation.Click 111 txtConsole.Text = "Element is at location " & _ arrayList.IndexOf(txtInput.Text) End Sub ' cmdLocation_Click 115 ' trim arrayList to current size Private Sub cmdTrim_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdTrim.Click 119 arrayList.TrimToSize() txtConsole.Text = "Vector trimmed to size" End Sub ' cmdTrim_Click 123 ' show arrayList current size and capacity Private Sub cmdStatistics_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdStatistics.Click 127 txtConsole.Text = "Size = " & arrayList.Count & _ "; capacity = " & arrayList.Capacity End Sub ' cmdStatistics_Click 131 ' display contents of arrayList Private Sub cmdDisplay_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdDisplay.Click 135 FrmArrayList.vb When the user clicks Trim, event handler cmdTrim_Click invokes method TrimToSize to set the Capacity property so that it is equal to the Count property When the user clicks Statistics, cmdStatistics_Click uses the Count and Capacity properties to display the current number of elements in the ArrayList and the maximum number of elements that can be stored without the allocation of more memory to the ArrayList. When the user clicks Display, cmdDisplay_Click outputs the contents of the ArrayList
71
136 Dim enumerator As IEnumerator = arrayList.GetEnumerator()
Dim buffer As StringBuilder = New StringBuilder() 138 While enumerator.MoveNext() buffer.Append(enumerator.Current & " ") End While 142 txtConsole.Text = buffer.ToString() End Sub ' cmdDisplay_Click 145 146 End Class ' FrmArrayList FrmArrayList.vb
72
23.7 Collection Classes FrmArrayList.vb
73
StackTest.vb constructor
1 ' Fig : StackTest.vb 2 ' Demonstrates class Stack functionality. 3 4 Imports System.Collections 5 Imports System.Text 6 Imports System.Windows.Forms 7 8 Public Class FrmStackTest Inherits Form 10 ' Buttons invoking Stack functionality Friend WithEvents cmdPush As Button Friend WithEvents cmdPop As Button Friend WithEvents cmdPeek As Button Friend WithEvents cmdIsEmpty As Button Friend WithEvents cmdSearch As Button Friend WithEvents cmdDisplay As Button 18 ' TextBox receives input from user Friend WithEvents txtInput As TextBox Friend WithEvents lblStatus As Label Friend WithEvents lblEnter As Label 23 Private stack As Stack 25 Public Sub New() MyBase.New() 28 InitializeComponent() 30 stack = New Stack() ' create stack End Sub ' New 33 ' Visual Studio .NET generated code 35 StackTest.vb constructor The FrmStackTest constructor creates a Stack with the default initial capacity of 10
74
36 ' push element onto stack
Private Sub cmdPush_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdPush.Click 39 Stack.Push(txtInput.Text) lblStatus.Text = "Pushed: " & txtInput.Text End Sub ' cmdPush_Click 43 ' pop element from stack Private Sub cmdPop_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdPop.Click 47 ' pop element Try lblStatus.Text = "Popped: " & stack.Pop() 51 ' print message if stack is empty Catch invalidOperation As InvalidOperationException lblStatus.Text = invalidOperation.ToString() End Try 56 End Sub ' cmdPop_Click 58 ' peek at top element of stack Private Sub cmdPeek_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdPeek.Click 62 ' view top element Try lblStatus.Text = "Top: " & stack.Peek() 66 ' print message if stack is empty Catch invalidOperation As InvalidOperationException lblStatus.Text = invalidOperation.ToString() End Try Event handler cmdPush_Click uses method Push to add a user-specified string to the Stack StackTest.vb Event handler cmdPop_Click calls method Pop to remove an object from the Stack Event handler cmdPeek_Click calls method Peek to view the object on top of the Stack
75
Event handler cmdIsEmpty_Click determines whether the Stack is empty by comparing the Stack’s Count property to zero 71 End Sub ' cmdPeek_Click 73 ' determine whether stack is empty Private Sub cmdIsEmpty_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdIsEmpty.Click 77 If stack.Count = 0 Then lblStatus.Text = "Stack is empty" Else lblStatus.Text = "Stack is not empty" End If 83 End Sub ' cmdIsEmpty_Click 85 ' determine whether specified element is on stack Private Sub cmdSearch_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdSearch.Click 89 If stack.Contains(txtInput.Text) Then lblStatus.Text = txtInput.Text & " found" Else lblStatus.Text = txtInput.Text & " not found" End If 95 End Sub ' cmdSearch_Click 97 ' display stack contents Private Sub cmdDisplay_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdDisplay.Click 101 Dim enumerator As IEnumerator = stack.GetEnumerator() Dim buffer As StringBuilder = New StringBuilder() 104 StackTest.vb Event handler cmdSearch_Click uses Stack method Contains to determine whether the Stack contains the specified object specified as its argument Event handler cmdDisplay_Click uses an IEnumerator to traverse the Stack and display its contents
76
StackTest.vb 105 While enumerator.MoveNext()
buffer.Append(enumerator.Current & " ") End While 108 lblStatus.Text = buffer.ToString() End Sub ' cmdDisplay_Click 111 112 End Class ' FrmStackTest StackTest.vb
77
23.7 Collection Classes StackTest.vb
78
FrmHashTableTest.vb constructor
1 ' Fig : FrmHashTableTest.vb 2 ' Demonstrate class Hashtable functionality. 3 4 Imports System.Collections 5 Imports System.Text 6 Imports System.Windows.Forms 7 8 Public Class FrmHashTableTest Inherits Form 10 ' Buttons invoke Hashtable functionality Friend WithEvents cmdAdd As Button Friend WithEvents cmdGet As Button Friend WithEvents cmdRemove As Button Friend WithEvents cmdEmpty As Button Friend WithEvents cmdContains As Button Friend WithEvents cmdClear As Button Friend WithEvents cmdListObjects As Button Friend WithEvents cmdListKeys As Button 20 ' TextBoxes enable user to input hashtable data Friend WithEvents txtFirst As TextBox Friend WithEvents txtLast As TextBox Friend WithEvents txtConsole As TextBox 25 Friend WithEvents lblFirst As Label Friend WithEvents lblLast As Label Friend WithEvents lblStatus As Label 29 Private table As Hashtable 31 Public Sub New() MyBase.New() 34 FrmHashTableTest.vb constructor
79
35 'This call is required by the Windows Form Designer.
InitializeComponent() 37 table = New Hashtable() ' create Hashtable object End Sub ' New 40 ' Visual Studio .NET generated code 42 ' add last name and CEmployee object to table Private Sub cmdAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdAdd.Click 46 Dim employee As New CEmployee(txtFirst.Text, txtLast.Text) 48 ' add new key/value pair Try table.Add(txtLast.Text, employee) lblStatus.Text = "Put: " & employee.ToString() 53 ' if key does not exist or is in table, throw exception Catch argumentException As ArgumentException lblStatus.Text = argumentException.ToString() End Try 58 End Sub ' cmdAdd_Click 60 ' get object for given key Private Sub cmdGet_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdGet.Click 64 Dim result As Object = table(txtLast.Text) 66 Event handler cmdAdd_Click reads the first name and last name of an employee from the user interface, creates an object of class CEmployee and adds the CEmployee to the HashTable FrmHashTableTest.vb Event handler cmdGet_Click retrieves the object associated with a specified key using the Hashtable‘s subscript operator
80
67 If Not result Is Nothing Then
lblStatus.Text = "Get: " & result.ToString() Else lblStatus.Text = "Get: " & txtLast.Text & " not in table" End If 72 End Sub ' cmdGet_Click 74 ' remove key/value pair from table Private Sub cmdRemove_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdRemove.Click 78 table.Remove(txtLast.Text) lblStatus.Text = "Object Removed" End Sub ' cmdRemove_Click 82 ' determine whether table is empty Private Sub cmdEmpty_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdEmpty.Click 86 lblStatus.Text = "Table is " 88 If table.Count = 0 Then lblStatus.Text &= "empty" Else lblStatus.Text &= "not empty" End If 94 End Sub ' cmdEmpty_Click 96 ' determine whether table contains specified key Private Sub cmdContains_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdContains.Click 100 Event handler cmdRemove_Click invokes Hashtable method Remove to delete a key and its associated object from the Hashtable FrmHashTableTest.vb Event handler cmdEmpty_Click uses Hashtable property Count to determine whether the Hashtable is empty Event handler cmdContains_Click invokes Hashtable method ContainsKey to determine whether the Hashtable contains the specified key
81
Event handler cmdClear_Click invokes Hashtable method Clear to delete all Hashtable entries
lblStatus.Text = "Contains key: " & _ table.ContainsKey(txtLast.Text) End Sub ' cmdContains_Click 104 ' discard all table contents Private Sub cmdClear_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdClear.Click 108 table.Clear() lblStatus.Text = "Clear: Table is now empty" End Sub ' cmdClear_Click 112 ' display list of all objects in table Private Sub cmdListObjects_Click( _ ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles cmdListObjects.Click 117 Dim enumerator As IDictionaryEnumerator = _ table.GetEnumerator() 120 Dim buffer As StringBuilder = New StringBuilder() 122 While enumerator.MoveNext() buffer.Append(Convert.ToString(enumerator.Value) & _ vbCrLf) End While 127 txtConsole.Text = buffer.ToString() End Sub ' cmdListObjects_Click 130 ' display list of keys in table Private Sub cmdListKeys_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdListKeys.Click 134 FrmHashTableTest.vb Event handler cmdListObjects_Click uses property Value of the enumerator to output the objects in the Hashtable Event handler cmdListKeys_Click uses the Key property of the enumerator to output the keys in the Hashtable
82
FrmHashTableTest.vb 135 Dim enumerator As IDictionaryEnumerator = _
table.GetEnumerator() 137 Dim buffer As StringBuilder = New StringBuilder() 139 While enumerator.MoveNext() buffer.Append(enumerator.Key & vbCrLf) End While 143 txtConsole.Text = buffer.ToString() End Sub ' cmdListKeys_Click 146 147 End Class ' FrmHashTableTest FrmHashTableTest.vb
83
23.7 Collection Classes FrmHashTableTest.vb
84
23.7 Collection Classes FrmHashTableTest.vb
85
Employee.vb 1 ' Fig. 23.31: Employee.vb
2 ' Class CEmployee for use with HashTable. 3 4 Public Class CEmployee Private firstName, lastName As String 6 Public Sub New(ByVal first As String, ByVal last As String) firstName = first lastName = last End Sub ' New 11 ' return Employee first and last names as String Public Overrides Function ToString() As String Return firstName & " " & lastName End Function ' ToString 16 17 End Class ' CEmployee Employee.vb
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.