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 23.6.1 Binary Search Tree of Integer Values 23.6.2 Binary Search Tree of IComparable Objects 23.7 Collection Classes 23.7.1 Class Array 23.7.2 Class ArrayList 23.7.3 Class Stack 23.7.4 Class Hashtable
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
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
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
Private instance variables mData and mNextNode 1 ' Fig. 23.01: Node.vb 2 ' Self-referential Node class. 3 4 Class CNode 5 Private mData As Integer 6 Private mNextNode As CNode 7 8 Public Sub New(ByVal dataValue As Integer) 9 ' constructor body 10 End Sub ' New 11 12 ' Property Data 13 Public Property Data() As Integer 14 15 Get 16 ' get body 17 End Get 18 19 Set(ByVal dataValue As Integer) 20 ' set body 21 End Set 22 23 End Property ' Data 24 25 ' Property NextNode 26 Public Property NextNode As CNode 27 28 Get 29 ' get next node 30 End Get 31 32 Set(ByVal nodeValue As CNode) 33 ' set next node 34 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
36 End Property ' NextNode 37 38 End Class 'CNode Node.vb
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
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
23.3 Linked Lists 15 10 Fig. 23.2 Self-referential class objects linked together. H D …… Q firstNode lastNode Fig. 23.3 Linked-list graphical representation.
1 ' Fig. 23.04: ListNodes.vb 2 ' Class to represent one node in a CList. 3 4 Public Class CListNode 5 Private mData As Object 6 Private mNextNode As CListNode 7 8 ' create CListNode with dataValue in list 9 Public Sub New(ByVal dataValue As Object) 10 MyClass.New(dataValue, Nothing) 11 End Sub ' New 12 13 ' create CListNode with dataValue and nextNodeValue in list 14 Public Sub New(ByVal dataValue As Object, _ 15 ByVal nextNodeValue As Object) 16 17 mData = dataValue 18 mNextNode = nextNodeValue 19 End Sub ' New 20 21 ' property Data 22 Public ReadOnly Property Data() As Object 23 24 Get 25 Return mData 26 End Get 27 28 End Property ' Data 29 30 ' property mNext 31 Public Property NextNode() As CListNode 32 33 Get 34 Return mNextNode 35 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
ListNodes.vb 36 37 Set(ByVal value As CListNode) 38 mNextNode = value 39 End Set 40 41 End Property ' NextNode 42 43 End Class ' CListNode ListNodes.vb
The constructors for Clist initialize both references to Nothing 1 ' Fig. 23.05: List.vb 2 ' Class CList definition. 3 4 Public Class CList 5 Private firstNode As CListNode 6 Private lastNode As CListNode 7 Private name As String 8 9 ' construct empty List with specified name 10 Public Sub New(ByVal listName As String) 11 name = listName 12 firstNode = Nothing 13 lastNode = Nothing 14 End Sub ' New 15 16 ' construct empty List with "list" as its name 17 Public Sub New() 18 MyClass.New("list") 19 End Sub ' New 20 21 ' insert object at front of List 22 Public Sub InsertAtFront(ByVal insertItem As Object) 23 24 SyncLock (Me) ' ensure thread safe 25 26 ' if this list is empty, create node 27 If IsEmpty() Then 28 lastNode = New CListNode(insertItem) 29 firstNode = lastNode 30 Else ' create node and insert before first node 31 firstNode = New CListNode(insertItem, firstNode) 32 End If 33 34 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
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 36 End Sub ' InsertAtFront 37 38 ' insert object at end of List 39 Public Sub InsertAtBack(ByVal insertItem As Object) 40 41 SyncLock (Me) ' ensure thread safety 42 43 ' if list is empty create node and set firstNode 44 If IsEmpty() Then 45 lastNode = New CListNode(insertItem) 46 firstNode = lastNode 47 Else ' create node and insert after last node 48 lastNode.NextNode = New CListNode(insertItem) 49 lastNode = lastNode.NextNode 50 End If 51 52 End SyncLock 53 54 End Sub ' InsertAtBack 55 56 ' remove first node from list 57 Public Function RemoveFromFront() As Object 58 59 SyncLock (Me) ' ensure thread safety 60 Dim removeItem As Object = Nothing 61 62 ' throw exception if removing node from empty list 63 If IsEmpty() Then 64 Throw New EmptyListException(name) 65 End If 66 67 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
List.vb method RemoveFromBack 69 ' reset firstNode and lastNode references 70 If firstNode Is lastNode Then 71 firstNode = Nothing 72 lastNode = Nothing 73 Else 74 firstNode = firstNode.NextNode 75 End If 76 77 Return removeItem ' return removed item 78 79 End SyncLock 80 81 End Function ' RemoveFromFront 82 83 ' remove last node from CList 84 Public Function RemoveFromBack() As Object 85 86 SyncLock (Me) ' ensure thread safe 87 Dim removeItem As Object = Nothing 88 89 ' throw exception if removing node from empty list 90 If IsEmpty() Then 91 Throw New EmptyListException(name) 92 End If 93 94 removeItem = lastNode.Data ' retrieve data 95 96 ' reset firstNode and last node references 97 If firstNode Is lastNode Then 98 lastNode = Nothing 99 firstNode = lastNode 100 Else 101 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
List.vb method IsEmpty Print 103 ' loop while current node is not lastNode 104 While (Not (current.NextNode Is lastNode)) 105 current = current.NextNode ' move to next node 106 End While 107 108 ' current is new lastNode 109 lastNode = current 110 current.NextNode = Nothing 111 End If 112 113 Return removeItem ' return removed data 114 115 End SyncLock 116 117 End Function ' RemoveFromBack 118 119 ' return true if list is empty 120 Public Function IsEmpty() As Boolean 121 122 SyncLock (Me) 123 124 If firstNode Is Nothing Then 125 Return True 126 Else 127 Return False 128 End If 129 130 End SyncLock 131 132 End Function ' IsEmpty 133 134 ' output List contents 135 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
137 SyncLock (Me) 138 139 If IsEmpty() Then 140 Console.WriteLine("Empty " & name) 141 142 Return 143 End If 144 145 Console.Write("The " & name & " is: ") 146 147 Dim current As CListNode = firstNode 148 149 ' output current node data while not at end of list 150 While Not current Is Nothing 151 Console.Write(current.Data & " ") 152 current = current.NextNode 153 End While 154 155 Console.WriteLine(vbCrLf) 156 157 End SyncLock 158 159 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.
EmptyListException.vb Define EmptyListException constructor 1 ' Fig. 23.06: EmptyListException.vb 2 ' Class EmptyListException definition. 3 4 Public Class EmptyListException 5 Inherits ApplicationException 6 7 Public Sub New(ByVal name As String) 8 MyBase.New("The " & name & " is empty") 9 End Sub ' New 10 11 End Class ' EmptyListException EmptyListException.vb Define EmptyListException constructor
ListTest.vb Define modListTest main 1 ' Fig. 23.07: ListTest.vb 2 ' Testing class CList. 3 4 ' Deitel namespaces 5 Imports LinkedListLibrary 6 7 Module modListTest 8 9 Sub Main() 10 Dim list As CList = New CList() ' create CList container 11 12 ' create data to store in CList 13 Dim aBoolean As Boolean = True 14 Dim aCharacter As Char = "$"c 15 Dim anInteger As Integer = 34567 16 Dim aString As String = "hello" 17 18 ' use CList insert methods 19 list.InsertAtFront(aBoolean) ' insert Boolean at front 20 list.Print() 21 22 list.InsertAtFront(aCharacter) ' insert Char at front 23 list.Print() 24 25 list.InsertAtBack(anInteger) ' insert Integer at back 26 list.Print() 27 28 list.InsertAtBack(aString) ' insert String at back 29 list.Print() 30 31 ' use CList remove methods 32 Dim removedObject As Object 33 34 ' remove data from list and print after each removal 35 Try ListTest.vb Define modListTest main
ListTest.vb 36 37 ' remove object from front of list 38 removedObject = list.RemoveFromFront() 39 Console.WriteLine(Convert.ToString(removedObject) & _ 40 " removed") 41 42 list.Print() 43 44 ' remove object from front of list 45 removedObject = list.RemoveFromFront() 46 Console.WriteLine(Convert.ToString(removedObject) & _ 47 " removed") 48 49 list.Print() 50 51 ' remove object from back of list 52 removedObject = list.RemoveFromBack() 53 Console.WriteLine(Convert.ToString(removedObject) & _ 54 " removed") 55 56 list.Print() 57 58 ' remove object from back of list 59 removedObject = list.RemoveFromBack() 60 Console.WriteLine(Convert.ToString(removedObject) & _ 61 " removed") 62 63 list.Print() 64 65 ' Catch exception if list is empty 66 Catch emptyListException As EmptyListException 67 Console.Error.WriteLine(vbCrLf & _ 68 Convert.ToString(emptyListException)) 69 70 End Try ListTest.vb
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 34567 hello $ removed The list is: True 34567 hello True removed The list is: 34567 hello hello removed The list is: 34567 34567 removed Empty list
23.3 Linked Lists 11 7 12 new ListNode (a) firstNode (b) Fig. 23.8 InsertAtFront graphical representation.
23.3 Linked Lists (a) 7 12 New ListNode 11 5 firstNode lastNode (b) Fig. 23.9 InsertAtBack graphical representation.
23.3 Linked Lists (a) 7 12 lastNode 11 5 firstNode (b) removeItem Fig. 23.10 RemoveFromFront graphical representation.
23.3 Linked Lists (a) 7 12 lastNode 11 5 firstNode (b) current removeItem Fig. 23.11 RemoveFromBack graphical representation.
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
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 9 Inherits CList 10 11 ' pass name "stack" to CList constructor 12 Public Sub New() 13 MyBase.New("stack") 14 End Sub ' New 15 16 ' place dataValue at top of stack by inserting dataValue at 17 ' front of linked list 18 Public Sub Push(ByVal dataValue As Object) 19 MyBase.InsertAtFront(dataValue) 20 End Sub ' Push 21 22 ' remove item from top of stack by removing item at front of 23 ' linked list 24 Public Function Pop() As Object 25 Return MyBase.RemoveFromFront() 26 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
StackTest.vb main objects to Push on the stack 1 ' Fig. 23.13: 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 11 Sub Main() 12 Dim stack As CStackInheritance = New CStackInheritance() 13 14 ' create objects to store in stack 15 Dim aBoolean As Boolean = True 16 Dim aCharacter As Char = Convert.ToChar("$") 17 Dim anInteger As Integer = 34567 18 Dim aString As String = "hello" 19 20 ' use method Push to add items to stack 21 stack.Push(aBoolean) ' add Boolean 22 stack.Print() 23 24 stack.Push(aCharacter) ' add Char 25 stack.Print() 26 27 stack.Push(anInteger) ' add Integer 28 stack.Print() 29 30 stack.Push(aString) ' add String 31 stack.Print() 32 33 ' use method Pop to remove items from stack 34 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
StackTest.vb Pop the objects off the stack 36 ' remove items from stack 37 Try 38 39 ' pop item and output removed item 40 While True 41 removedObject = stack.Pop() 42 Console.WriteLine(removedObject & " popped") 43 stack.Print() 44 End While 45 46 ' catch exception if Pop was called while stack empty 47 Catch emptyListException As EmptyListException 48 Console.Error.WriteLine(emptyListException.StackTrace) 49 End Try 50 51 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: 34567 $ True The stack is: hello 34567 $ True hello popped 34567 popped
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
StackComposition.vb constructor Push method Pop method IsEmpty Print 1 ' Fig. 23.14: 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 9 Private stack As CList 10 11 ' construct empty stack 12 Public Sub New() 13 stack = New CList("stack") 14 End Sub ' New 15 16 ' add object to stack 17 Public Sub Push(ByVal dataValue As Object) 18 stack.InsertAtFront(dataValue) 19 End Sub ' Push 20 21 ' remove object from stack 22 Public Function Pop() As Object 23 Return stack.RemoveFromFront() 24 End Function ' Pop 25 26 ' determine whether stack is empty 27 Public Function IsEmpty() As Boolean 28 Return stack.IsEmpty() 29 End Function ' IsEmpty 30 31 ' output stack content 32 Public Sub Print() 33 stack.Print() 34 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
35 36 End Class ' CStackComposition StackComposition.vb
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
Inherits the Clist class 1 ' Fig. 23.15: 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 9 Inherits CList 10 11 ' pass name "queue" to CList constructor 12 Public Sub New() 13 MyBase.New("queue") 14 End Sub 15 16 ' place dataValue at end of queue by inserting dataValue at end 17 ' of linked list 18 Public Sub Enqueue(ByVal dataValue As Object) 19 MyBase.InsertAtBack(dataValue) 20 End Sub ' Enqueue 21 22 ' remove item from front of queue by removing item at front of 23 ' linked list 24 Public Function Dequeue() As Object 25 Return MyBase.RemoveFromFront() 26 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
Objects are created and then added to the queue 1 ' Fig. 23.16: 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 11 Sub Main() 12 Dim queue As CQueueInheritance = New CQueueInheritance() 13 14 ' create data to store in queue 15 Dim aBoolean As Boolean = True 16 Dim aCharacter As Char = Convert.ToChar("$") 17 Dim anInteger As Integer = 34567 18 Dim aString As String = "hello" 19 20 ' use method Enqueue to add items to queue 21 queue.Enqueue(aBoolean) ' add Boolean 22 queue.Print() 23 24 queue.Enqueue(aCharacter) ' add Char 25 queue.Print() 26 27 queue.Enqueue(anInteger) ' add Integer 28 queue.Print() 29 30 queue.Enqueue(aString) ' add String 31 queue.Print() 32 33 ' use method Dequeue to remove items from queue 34 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
QueueTest.vb removing the objects from the queue 36 ' remove items from queue 37 Try 38 39 ' dequeue item and output removed item 40 While True 41 removedObject = queue.Dequeue() 42 Console.WriteLine(removedObject & " dequeue") 43 queue.Print() 44 End While 45 46 ' if exception occurs, print stack trace 47 Catch emptyListException As EmptyListException 48 Console.Error.WriteLine(emptyListException.StackTrace) 49 End Try 50 51 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 $ 34567 hello True dequeue The queue is: $ 34567 hello $ dequeue The queue is: 34567 hello
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
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
23.6 Trees B A D C Fig. 23.17 Binary tree graphical representation.
23.6 Trees 47 25 77 11 7 17 65 93 68 43 31 44 Fig. 23.18 A binary search tree containing 12 values.
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. 23.19: TreeNode.vb 2 ' Class CTreeNode represents a node in a CTree. 3 4 Public Class CTreeNode 5 Private mLeftNode As CTreeNode 6 Private mData As Integer 7 Private mRightNode As CTreeNode 8 9 ' initialize data and make that a leaf node 10 Public Sub New(ByVal nodeData As Integer) 11 mData = nodeData 12 mRightNode = Nothing ' node has no children 13 LeftNode = Nothing ' node has no children 14 End Sub ' New 15 16 ' property LeftNode 17 Public Property LeftNode() As CTreeNode 18 19 Get 20 Return mLeftNode 21 End Get 22 23 Set(ByVal value As CTreeNode) 24 mLeftNode = value 25 End Set 26 27 End Property ' LeftNode 28 29 ' property Data 30 Public Property Data() As Integer 31 32 Get 33 Return mData 34 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.
TreeNode.vb Property RightNode method Insert 36 Set(ByVal value As Integer) 37 mData = value 38 End Set 39 40 End Property ' Data 41 42 ' property RightNode 43 Public Property RightNode() As CTreeNode 44 45 Get 46 Return mRightNode 47 End Get 48 49 Set(ByVal value As CTreeNode) 50 mRightNode = value 51 End Set 52 53 End Property ' RightNode 54 55 ' insert node into tree 56 Public Sub Insert(ByVal insertValue As Integer) 57 58 ' insert in left subtree 59 If insertValue < mData Then 60 61 ' insert new CTreeNode 62 If mLeftNode Is Nothing Then 63 LeftNode = New CTreeNode(insertValue) 64 65 ' continue traversing left subtree 66 Else 67 LeftNode.Insert(insertValue) 68 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.
TreeNode.vb 70 ' insert in right subtree 71 ElseIf insertValue > mData Then 72 73 ' insert new CTreeNode 74 If RightNode Is Nothing Then 75 RightNode = New CTreeNode(insertValue) 76 77 ' continue traversing right subtree 78 Else 79 RightNode.Insert(insertValue) 80 End If 81 82 End If 83 84 End Sub ' Insert 85 86 End Class ' CTreeNode TreeNode.vb
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. 23.20: Tree.vb 2 ' Class CTree is a tree containing CTreeNodes. 3 4 Public Class CTree 5 Private root As CTreeNode 6 7 ' construct an empty CTree of integers 8 Public Sub New() 9 root = Nothing 10 End Sub ' New 11 12 ' insert new node in binary search tree 13 Public Sub InsertNode(ByVal insertValue As Integer) 14 15 SyncLock (Me) 16 17 ' if node does not exist, create node 18 If root Is Nothing Then 19 root = New CTreeNode(insertValue) 20 Else ' otherwise insert node into tree 21 root.Insert(insertValue) 22 End If 23 24 End SyncLock 25 26 End Sub ' InsertNode 27 28 ' begin preorder traversal 29 Public Sub PreorderTraversal() 30 31 SyncLock (Me) 32 PreorderHelper(root) 33 End SyncLock 34 35 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.
36 37 ' recursive method to perform preorder traversal 38 Private Sub PreorderHelper(ByVal node As CTreeNode) 39 40 If node Is Nothing Then 41 Return 42 End If 43 44 ' output node data 45 Console.Write(node.Data & " ") 46 47 ' traverse left subtree 48 PreorderHelper(node.LeftNode) 49 50 ' traverse right subtree 51 PreorderHelper(node.RightNode) 52 53 End Sub ' PreorderHelper 54 55 ' begin inorder traversal 56 Public Sub InorderTraversal() 57 58 SyncLock (Me) 59 InorderHelper(root) 60 End SyncLock 61 62 End Sub ' InorderTraversal 63 64 ' recursive method to perform inorder traversal 65 Private Sub InorderHelper(ByVal node As CTreeNode) 66 67 If node Is Nothing Then 68 Return 69 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
Tree.vb method PostorderTraversal helper method PostorderHelper 71 ' traverse left subtree 72 InorderHelper(node.LeftNode) 73 74 ' output node data 75 Console.Write(node.Data & " ") 76 77 ' traverse right subtree 78 InorderHelper(node.RightNode) 79 80 End Sub ' InorderHelper 81 82 ' begin postorder traversal 83 Public Sub PostorderTraversal() 84 85 SyncLock (Me) 86 PostorderHelper(root) 87 End SyncLock 88 89 End Sub ' PostorderTraversal 90 91 ' recursive method to perform postorder traversal 92 Private Sub PostorderHelper(ByVal node As CTreeNode) 93 94 If node Is Nothing Then 95 Return 96 End If 97 98 ' traverse left subtree 99 PostorderHelper(node.LeftNode) 100 101 ' traverse right subtree 102 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
Tree.vb 104 ' output node data 105 Console.Write(node.Data & " ") 106 107 End Sub ' PostorderHelper 108 109 End Class ' CTree Tree.vb
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 9 ' test class CTree 10 Sub Main() 11 Dim tree As CTree = New CTree() 12 Dim insertValue As Integer 13 Dim i As Integer 14 15 Console.WriteLine("Inserting Values: ") 16 Dim randomNumber As Random = New Random() 17 18 ' insert 10 random integers from 0-99 in tree 19 For i = 1 To 10 20 insertValue = randomNumber.Next(100) 21 Console.Write(insertValue & " ") 22 tree.InsertNode(insertValue) 23 Next 24 25 ' perform preorder traversal of tree 26 Console.WriteLine(vbCrLf & vbCrLf & "Preorder Traversal") 27 tree.PreOrderTraversal() 28 29 ' perform inorder traversal of tree 30 Console.WriteLine(vbCrLf & vbCrLf & "Inorder Traversal") 31 tree.InOrderTraversal() 32 TreeTest.vb
TreeTest.vb 33 ' perform postorder traversal of tree 34 Console.WriteLine(vbCrLf & vbCrLf & "Postorder Traversal") 35 tree.PostOrderTraversal() 36 37 Console.WriteLine() 38 End Sub ' Main 39 40 End Module ' modTreeTest TreeTest.vb Inserting Values: 83 13 83 96 81 26 25 13 10 89 Preorder Traversal 83 13 10 81 26 25 96 89 Inorder Traversal 10 13 25 26 81 83 89 96 Postorder Traversal 10 25 26 81 13 89 96
23.6 Trees 27 13 42 6 33 48 17 Fig. 23.22 A binary search tree.
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. 23.23: TreeNode2.vb 2 ' Class CTreeNode uses IComparable objects for objects 3 4 Public Class CTreeNode 5 Private mLeftNode As CTreeNode 6 Private mData As IComparable 7 Private mRightNode As CTreeNode 8 9 ' initialize data and make this a leaf node 10 Public Sub New(ByVal nodeData As IComparable) 11 mData = nodeData 12 mRightNode = Nothing ' node has no children 13 LeftNode = Nothing ' node has no children 14 End Sub ' New 15 16 ' property LeftNode 17 Public Property LeftNode() As CTreeNode 18 19 Get 20 Return mLeftNode 21 End Get 22 23 Set(ByVal value As CTreeNode) 24 mLeftNode = value 25 End Set 26 27 End Property ' LeftNode 28 29 ' property Data 30 Public Property Data() As IComparable 31 32 Get 33 Return mData 34 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
36 Set(ByVal value As IComparable) 37 mData = value 38 End Set 39 40 End Property ' Data 41 42 ' property RightNode 43 Public Property RightNode() As CTreeNode 44 45 Get 46 Return mRightNode 47 End Get 48 49 Set(ByVal value As CTreeNode) 50 mRightNode = value 51 End Set 52 53 End Property ' RightNode 54 55 ' insert node into tree 56 Public Sub Insert(ByVal insertValue As IComparable) 57 58 'insert in left subtree 59 If insertValue.CompareTo(mData) < 0 Then 60 61 ' insert new TreeNode 62 If mLeftNode Is Nothing Then 63 LeftNode = New CTreeNode(insertValue) 64 65 ' continue traversing left subtree 66 Else 67 LeftNode.Insert(insertValue) 68 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
TreeNode2.vb 70 ' insert in right subtree 71 ElseIf insertValue.CompareTo(mData) Then 72 73 ' insert new TreeNode 74 If RightNode Is Nothing Then 75 RightNode = New CTreeNode(insertValue) 76 77 ' continue traversing right subtree 78 Else 79 RightNode.Insert(insertValue) 80 End If 81 82 End If 83 84 End Sub ' Insert 85 86 End Class ' CTreeNode TreeNode2.vb
1 ' Fig. 23.24: Tree2.vb 2 ' Class CTree contains nodes with IComparable data 3 4 Public Class CTree 5 Private root As CTreeNode 6 7 ' construct an empty CTree of integers 8 Public Sub New() 9 root = Nothing 10 End Sub ' New 11 12 ' insert new node in binary search tree 13 Public Sub InsertNode(ByVal insertValue As IComparable) 14 15 SyncLock (Me) 16 17 ' if node does not exist, create one 18 If root Is Nothing Then 19 root = New CTreeNode(insertValue) 20 Else ' otherwise insert node in tree 21 root.Insert(insertValue) 22 End If 23 24 End SyncLock 25 26 End Sub ' InsertNode 27 28 ' begin preorder traversal 29 Public Sub PreorderTraversal() 30 31 SyncLock (Me) 32 PreorderHelper(root) 33 End SyncLock 34 35 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
36 37 ' recursive method to perform preorder traversal 38 Private Sub PreorderHelper(ByVal node As CTreeNode) 39 40 If node Is Nothing Then 41 Return 42 End If 43 44 ' output node data 45 Console.Write(Convert.ToString(node.Data) & " ") 46 47 ' traverse left subtree 48 PreOrderHelper(node.LeftNode) 49 50 ' traverse right subtree 51 PreOrderHelper(node.RightNode) 52 53 End Sub ' PreOrderHelper 54 55 ' begin inorder traversal 56 Public Sub InorderTraversal() 57 58 SyncLock (Me) 59 InorderHelper(root) 60 End SyncLock 61 62 End Sub ' InorderTraversal 63 64 ' recursive method to perform inorder traversal 65 Private Sub InorderHelper(ByVal node As CTreeNode) 66 67 If node Is Nothing Then 68 Return 69 End If 70 Tree2.vb helper method PreorderHelper method InorderTraversal helper method InorderHelper
Tree2.vb method PostorderTraversal helper method PostorderHelper 71 ' traverse left subtree 72 InorderHelper(node.LeftNode) 73 74 ' output node data 75 Console.Write(Convert.ToString(node.Data) & " ") 76 77 ' traverse right subtree 78 InorderHelper(node.RightNode) 79 80 End Sub ' InorderHelper 81 82 ' begin postorder traversal 83 Public Sub PostorderTraversal() 84 85 SyncLock (Me) 86 PostOrderHelper(root) 87 End SyncLock 88 89 End Sub ' PostorderTraversal 90 91 ' recursive method to perform postorder traversal 92 Private Sub PostorderHelper(ByVal node As CTreeNode) 93 94 If node Is Nothing Then 95 Return 96 End If 97 98 ' traverse left subtree 99 PostorderHelper(node.LeftNode) 100 101 ' traverse right subtree 102 PostorderHelper(node.RightNode) 103 104 ' output node data 105 Console.Write(Convert.ToString(node.Data) & " ") Tree2.vb method PostorderTraversal helper method PostorderHelper
106 107 End Sub ' PostorderHelper 108 109 End Class ' CTree Tree2.vb
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 9 ' test class CTree. 10 Sub Main() 11 Dim integerArray As Integer() = {8, 2, 4, 3, 1, 7, 5, 6} 12 Dim doubleArray As Double() = _ 13 {8.8, 2.2, 4.4, 3.3, 1.1, 7.7, 5.5, 6.6} 14 15 Dim stringArray As String() = {"eight", "two", "four", _ 16 "three", "one", "seven", "five", "six"} 17 18 ' create Integer tree 19 Dim integerTree As CTree = New CTree() 20 PopulateTree(integerArray, integerTree, "integerTree") 21 TraverseTree(integerTree, "integerTree") 22 23 ' create Double tree 24 Dim doubleTree As CTree = New CTree() 25 populateTree(doubleArray, doubleTree, "doubleTree") 26 TraverseTree(doubleTree, "doubleTree") 27 28 ' create String tree 29 Dim stringTree As CTree = New CTree() 30 populateTree(stringArray, stringTree, "stringTree") 31 TraverseTree(stringTree, "stringTree") 32 33 End Sub ' Main 34 TreeTest2.vb main
TreeTest2.vb 35 ' populate tree with array elements 36 Public Sub PopulateTree(ByVal array As Array, _ 37 ByVal tree As CTree, ByVal name As String) 38 39 Dim data As IComparable 40 Console.WriteLine(vbCrLf & "Inserting into " & name & ":") 41 42 For Each data In array 43 Console.Write(Convert.ToString(data) & " ") 44 tree.InsertNode(data) 45 Next 46 47 End Sub ' PopulateTree 48 49 ' perform traversals 50 Public Sub TraverseTree(ByVal tree As CTree, _ 51 ByVal treeType As String) 52 53 ' perform preorder traversal of tree 54 Console.WriteLine(vbCrLf & vbCrLf & _ 55 "Preorder Traversal of " & treeType) 56 57 tree.PreorderTraversal() 58 59 ' perform inorder traversal of tree 60 Console.WriteLine(vbCrLf & vbCrLf & _ 61 "Inorder Traversal of " & treeType) 62 63 tree.InorderTraversal() 64 65 ' perform postorder traversal of tree 66 Console.WriteLine(vbCrLf & vbCrLf & _ 67 "Postorder Traversal of " & treeType) 68 TreeTest2.vb
TreeTest2.vb 69 tree.PostorderTraversal() 70 71 Console.WriteLine(vbCrLf) 72 End Sub ' TraverseTree 73 74 End Module ' CTreeTest2 TreeTest2.vb Inserting into integerTree: 8 2 4 3 1 7 5 6 Preorder Traversal of integerTree 8 2 1 4 3 7 5 6 Inorder Traversal of integerTree 1 2 3 4 5 6 7 8 Postorder Traversal of integerTree 1 3 6 5 7 4 2 8 Inserting into doubleTree: 8.8 2.2 4.4 3.3 1.1 7.7 5.5 6.6 Preorder Traversal of doubleTree 8.8 2.2 1.1 4.4 3.3 7.7 5.5 6.6 Inorder Traversal of doubleTree 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 Postorder Traversal of doubleTree 1.1 3.3 6.6 5.5 7.7 4.4 2.2 8.8
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
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
1 ' Fig. 23.26: 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 9 Private integerValues As Integer() = {1, 2, 3, 4, 5, 6} 10 Private doubleValues As Double() = _ 11 {8.4, 9.3, 0.2, 7.9, 3.4} 12 13 Private integerValuesCopy(6) As Integer 14 Private output As String 15 16 ' build and display program output 17 Public Sub Start() 18 Dim result As Integer 19 20 output = "Initial Array Values:" & vbCrLf 21 PrintArray() ' output initial array contents 22 23 ' sort doubleValues 24 Array.Sort(doubleValues) 25 26 ' copy integerValues into integerValuesCopy 27 Array.Copy(integerValues, integerValuesCopy, _ 28 integerValues.Length) 29 30 output &= vbCrLf & vbCrLf & _ 31 "Array values after Sort and Copy:" & vbCrLf 32 33 PrintArray() ' output array contents 34 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
UsingArray.vb PrintArray method 36 ' search for value 5 in integerValues 37 result = Array.BinarySearch(integerValues, 5) 38 39 If result >= 0 Then 40 output &= "5 found at element " & result & _ 41 " in integerValues" 42 Else 43 output &= "5 not found" & " in integerValues" 44 End If 45 46 output &= vbCrLf 47 48 ' search for value 8763 in integerValues 49 result = Array.BinarySearch(integerValues, 8763) 50 51 If result >= 0 Then 52 output &= "8763 found at element " & _ 53 result & " in integerValues" 54 Else 55 output &= "8763 was not found" & " in integerValues" 56 End If 57 58 MessageBox.Show(output, "Using Class Array", _ 59 MessageBoxButtons.OK, MessageBoxIcon.Information) 60 61 End Sub ' Start 62 63 ' append array output to output string 64 Private Sub PrintArray() 65 Dim doubleElement As Double 66 Dim integerElement As Integer 67 68 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
UsingArray.vb main 70 ' output each element in array doubleValues 71 For Each doubleElement In doubleValues 72 output &= doubleElement & " " 73 Next 74 75 output &= vbCrLf & " integerValues: " 76 77 ' output each element in array integerValues 78 For Each integerElement In integerValues 79 output &= integerElement & " " 80 Next 81 82 output &= vbCrLf & " integerValuesCopy: " 83 84 ' output each element in array integerValuesCopy 85 For Each integerElement In integerValuesCopy 86 output &= integerElement & " " 87 Next 88 89 End Sub ' PrintArray 90 91 ' main entry point for application 92 Shared Sub Main() 93 Dim application As CUsingArray = New CUsingArray() 94 application.Start() 95 End Sub ' Main 96 97 End Class ' CUsingArray UsingArray.vb main
23.7 Collection Classes
23.7 Collection Classes Fig. 23.27 ArrayList methods (partial list).
Creates an ArrayList with an initial capacity of one element 1 ' Fig. 23.28: 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 9 Inherits Form 10 11 ' Buttons for invoking ArrayList functionality 12 Friend WithEvents cmdAdd As Button 13 Friend WithEvents cmdRemove As Button 14 Friend WithEvents cmdFirst As Button 15 Friend WithEvents cmdLast As Button 16 Friend WithEvents cmdIsEmpty As Button 17 Friend WithEvents cmdContains As Button 18 Friend WithEvents cmdLocation As Button 19 Friend WithEvents cmdTrim As Button 20 Friend WithEvents cmdStatistics As Button 21 Friend WithEvents cmdDisplay As Button 22 23 ' TextBox for user input 24 Friend WithEvents txtInput As TextBox 25 Friend WithEvents lblEnter As Label 26 27 Friend WithEvents txtConsole As TextBox ' TextBox for output 28 29 ' Visual Studio .NET generated code 30 31 ' ArrayList for manipulating Strings 32 Private arrayList As ArrayList = New ArrayList(1) 33 FrmArrayList.vb Creates an ArrayList with an initial capacity of one element
34 ' add item to end of arrayList 35 Private Sub cmdAdd_Click(ByVal sender As System.Object, _ 36 ByVal e As System.EventArgs) Handles cmdAdd.Click 37 38 arrayList.Add(txtInput.Text) 39 txtConsole.Text = "Added to end: " & txtInput.Text 40 txtInput.Clear() 41 End Sub ' cmdAdd_Click 42 43 'remove specified item from arrayList 44 Private Sub cmdRemove_Click(ByVal sender As System.Object, _ 45 ByVal e As System.EventArgs) Handles cmdRemove.Click 46 47 arrayList.Remove(txtInput.Text) 48 txtConsole.Text = "Removed: " & txtInput.Text 49 txtInput.Clear() 50 End Sub ' cmdRemove_Click 51 52 ' display first element 53 Private Sub cmdFirst_Click(ByVal sender As System.Object, _ 54 ByVal e As System.EventArgs) Handles cmdFirst.Click 55 56 ' get first element 57 Try 58 txtConsole.Text = "First element: " & arrayList(0) 59 60 ' show exception if no elements in arrayList 61 Catch outOfRange As ArgumentOutOfRangeException 62 txtConsole.Text = outOfRange.ToString() 63 End Try 64 65 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.
67 ' display last element 68 Private Sub cmdLast_Click(ByVal sender As System.Object, _ 69 ByVal e As System.EventArgs) Handles cmdLast.Click 70 71 ' get last element 72 Try 73 txtConsole.Text = "Last element: " & _ 74 arrayList(arrayList.Count - 1) 75 76 ' show exception if no elements in arrayList 77 Catch outOfRange As ArgumentOutOfRangeException 78 txtConsole.Text = outOfRange.ToString() 79 End Try 80 81 End Sub ' cmdLast_Click 82 83 ' determine whether arrayList is empty 84 Private Sub cmdIsEmpty_Click(ByVal sender As System.Object, _ 85 ByVal e As System.EventArgs) Handles cmdIsEmpty.Click 86 87 If arrayList.Count = 0 Then 88 txtConsole.Text = "arrayList is empty" 89 Else 90 txtConsole.Text = "arrayList is not empty" 91 End If 92 93 End Sub ' cmdIsEmpty_Click 94 95 ' determine whether arrayList contains specified object 96 Private Sub cmdContains_Click(ByVal sender As System.Object, _ 97 ByVal e As System.EventArgs) Handles cmdContains.Click 98 99 If arrayList.Contains(txtInput.Text) Then 100 txtConsole.Text = "arrayList contains " & _ 101 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
When the user clicks Location, event handler cmdIsEmpty_Click invokes ArrayList method IndexOf to determine the index of a particular object in the ArrayList 102 Else 103 txtConsole.Text = txtInput.Text & " not found" 104 End If 105 106 End Sub ' cmdContains_Click 107 108 ' determine location of specified object 109 Private Sub cmdLocation_Click(ByVal sender As System.Object, _ 110 ByVal e As System.EventArgs) Handles cmdLocation.Click 111 112 txtConsole.Text = "Element is at location " & _ 113 arrayList.IndexOf(txtInput.Text) 114 End Sub ' cmdLocation_Click 115 116 ' trim arrayList to current size 117 Private Sub cmdTrim_Click(ByVal sender As System.Object, _ 118 ByVal e As System.EventArgs) Handles cmdTrim.Click 119 120 arrayList.TrimToSize() 121 txtConsole.Text = "Vector trimmed to size" 122 End Sub ' cmdTrim_Click 123 124 ' show arrayList current size and capacity 125 Private Sub cmdStatistics_Click(ByVal sender As System.Object, _ 126 ByVal e As System.EventArgs) Handles cmdStatistics.Click 127 128 txtConsole.Text = "Size = " & arrayList.Count & _ 129 "; capacity = " & arrayList.Capacity 130 End Sub ' cmdStatistics_Click 131 132 ' display contents of arrayList 133 Private Sub cmdDisplay_Click(ByVal sender As System.Object, _ 134 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
136 Dim enumerator As IEnumerator = arrayList.GetEnumerator() 137 Dim buffer As StringBuilder = New StringBuilder() 138 139 While enumerator.MoveNext() 140 buffer.Append(enumerator.Current & " ") 141 End While 142 143 txtConsole.Text = buffer.ToString() 144 End Sub ' cmdDisplay_Click 145 146 End Class ' FrmArrayList FrmArrayList.vb
23.7 Collection Classes FrmArrayList.vb
StackTest.vb constructor 1 ' Fig. 23.29: 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 9 Inherits Form 10 11 ' Buttons invoking Stack functionality 12 Friend WithEvents cmdPush As Button 13 Friend WithEvents cmdPop As Button 14 Friend WithEvents cmdPeek As Button 15 Friend WithEvents cmdIsEmpty As Button 16 Friend WithEvents cmdSearch As Button 17 Friend WithEvents cmdDisplay As Button 18 19 ' TextBox receives input from user 20 Friend WithEvents txtInput As TextBox 21 Friend WithEvents lblStatus As Label 22 Friend WithEvents lblEnter As Label 23 24 Private stack As Stack 25 26 Public Sub New() 27 MyBase.New() 28 29 InitializeComponent() 30 31 stack = New Stack() ' create stack 32 End Sub ' New 33 34 ' Visual Studio .NET generated code 35 StackTest.vb constructor The FrmStackTest constructor creates a Stack with the default initial capacity of 10
36 ' push element onto stack 37 Private Sub cmdPush_Click(ByVal sender As System.Object, _ 38 ByVal e As System.EventArgs) Handles cmdPush.Click 39 40 Stack.Push(txtInput.Text) 41 lblStatus.Text = "Pushed: " & txtInput.Text 42 End Sub ' cmdPush_Click 43 44 ' pop element from stack 45 Private Sub cmdPop_Click(ByVal sender As System.Object, _ 46 ByVal e As System.EventArgs) Handles cmdPop.Click 47 48 ' pop element 49 Try 50 lblStatus.Text = "Popped: " & stack.Pop() 51 52 ' print message if stack is empty 53 Catch invalidOperation As InvalidOperationException 54 lblStatus.Text = invalidOperation.ToString() 55 End Try 56 57 End Sub ' cmdPop_Click 58 59 ' peek at top element of stack 60 Private Sub cmdPeek_Click(ByVal sender As System.Object, _ 61 ByVal e As System.EventArgs) Handles cmdPeek.Click 62 63 ' view top element 64 Try 65 lblStatus.Text = "Top: " & stack.Peek() 66 67 ' print message if stack is empty 68 Catch invalidOperation As InvalidOperationException 69 lblStatus.Text = invalidOperation.ToString() 70 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
Event handler cmdIsEmpty_Click determines whether the Stack is empty by comparing the Stack’s Count property to zero 71 72 End Sub ' cmdPeek_Click 73 74 ' determine whether stack is empty 75 Private Sub cmdIsEmpty_Click(ByVal sender As System.Object, _ 76 ByVal e As System.EventArgs) Handles cmdIsEmpty.Click 77 78 If stack.Count = 0 Then 79 lblStatus.Text = "Stack is empty" 80 Else 81 lblStatus.Text = "Stack is not empty" 82 End If 83 84 End Sub ' cmdIsEmpty_Click 85 86 ' determine whether specified element is on stack 87 Private Sub cmdSearch_Click(ByVal sender As System.Object, _ 88 ByVal e As System.EventArgs) Handles cmdSearch.Click 89 90 If stack.Contains(txtInput.Text) Then 91 lblStatus.Text = txtInput.Text & " found" 92 Else 93 lblStatus.Text = txtInput.Text & " not found" 94 End If 95 96 End Sub ' cmdSearch_Click 97 98 ' display stack contents 99 Private Sub cmdDisplay_Click(ByVal sender As System.Object, _ 100 ByVal e As System.EventArgs) Handles cmdDisplay.Click 101 102 Dim enumerator As IEnumerator = stack.GetEnumerator() 103 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
StackTest.vb 105 While enumerator.MoveNext() 106 buffer.Append(enumerator.Current & " ") 107 End While 108 109 lblStatus.Text = buffer.ToString() 110 End Sub ' cmdDisplay_Click 111 112 End Class ' FrmStackTest StackTest.vb
23.7 Collection Classes StackTest.vb
FrmHashTableTest.vb constructor 1 ' Fig. 23.30: 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 9 Inherits Form 10 11 ' Buttons invoke Hashtable functionality 12 Friend WithEvents cmdAdd As Button 13 Friend WithEvents cmdGet As Button 14 Friend WithEvents cmdRemove As Button 15 Friend WithEvents cmdEmpty As Button 16 Friend WithEvents cmdContains As Button 17 Friend WithEvents cmdClear As Button 18 Friend WithEvents cmdListObjects As Button 19 Friend WithEvents cmdListKeys As Button 20 21 ' TextBoxes enable user to input hashtable data 22 Friend WithEvents txtFirst As TextBox 23 Friend WithEvents txtLast As TextBox 24 Friend WithEvents txtConsole As TextBox 25 26 Friend WithEvents lblFirst As Label 27 Friend WithEvents lblLast As Label 28 Friend WithEvents lblStatus As Label 29 30 Private table As Hashtable 31 32 Public Sub New() 33 MyBase.New() 34 FrmHashTableTest.vb constructor
35 'This call is required by the Windows Form Designer. 36 InitializeComponent() 37 38 table = New Hashtable() ' create Hashtable object 39 End Sub ' New 40 41 ' Visual Studio .NET generated code 42 43 ' add last name and CEmployee object to table 44 Private Sub cmdAdd_Click(ByVal sender As System.Object, _ 45 ByVal e As System.EventArgs) Handles cmdAdd.Click 46 47 Dim employee As New CEmployee(txtFirst.Text, txtLast.Text) 48 49 ' add new key/value pair 50 Try 51 table.Add(txtLast.Text, employee) 52 lblStatus.Text = "Put: " & employee.ToString() 53 54 ' if key does not exist or is in table, throw exception 55 Catch argumentException As ArgumentException 56 lblStatus.Text = argumentException.ToString() 57 End Try 58 59 End Sub ' cmdAdd_Click 60 61 ' get object for given key 62 Private Sub cmdGet_Click(ByVal sender As System.Object, _ 63 ByVal e As System.EventArgs) Handles cmdGet.Click 64 65 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
67 If Not result Is Nothing Then 68 lblStatus.Text = "Get: " & result.ToString() 69 Else 70 lblStatus.Text = "Get: " & txtLast.Text & " not in table" 71 End If 72 73 End Sub ' cmdGet_Click 74 75 ' remove key/value pair from table 76 Private Sub cmdRemove_Click(ByVal sender As System.Object, _ 77 ByVal e As System.EventArgs) Handles cmdRemove.Click 78 79 table.Remove(txtLast.Text) 80 lblStatus.Text = "Object Removed" 81 End Sub ' cmdRemove_Click 82 83 ' determine whether table is empty 84 Private Sub cmdEmpty_Click(ByVal sender As System.Object, _ 85 ByVal e As System.EventArgs) Handles cmdEmpty.Click 86 87 lblStatus.Text = "Table is " 88 89 If table.Count = 0 Then 90 lblStatus.Text &= "empty" 91 Else 92 lblStatus.Text &= "not empty" 93 End If 94 95 End Sub ' cmdEmpty_Click 96 97 ' determine whether table contains specified key 98 Private Sub cmdContains_Click(ByVal sender As System.Object, _ 99 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
Event handler cmdClear_Click invokes Hashtable method Clear to delete all Hashtable entries 101 lblStatus.Text = "Contains key: " & _ 102 table.ContainsKey(txtLast.Text) 103 End Sub ' cmdContains_Click 104 105 ' discard all table contents 106 Private Sub cmdClear_Click(ByVal sender As System.Object, _ 107 ByVal e As System.EventArgs) Handles cmdClear.Click 108 109 table.Clear() 110 lblStatus.Text = "Clear: Table is now empty" 111 End Sub ' cmdClear_Click 112 113 ' display list of all objects in table 114 Private Sub cmdListObjects_Click( _ 115 ByVal sender As System.Object, ByVal e As System.EventArgs) _ 116 Handles cmdListObjects.Click 117 118 Dim enumerator As IDictionaryEnumerator = _ 119 table.GetEnumerator() 120 121 Dim buffer As StringBuilder = New StringBuilder() 122 123 While enumerator.MoveNext() 124 buffer.Append(Convert.ToString(enumerator.Value) & _ 125 vbCrLf) 126 End While 127 128 txtConsole.Text = buffer.ToString() 129 End Sub ' cmdListObjects_Click 130 131 ' display list of keys in table 132 Private Sub cmdListKeys_Click(ByVal sender As System.Object, _ 133 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
FrmHashTableTest.vb 135 Dim enumerator As IDictionaryEnumerator = _ 136 table.GetEnumerator() 137 138 Dim buffer As StringBuilder = New StringBuilder() 139 140 While enumerator.MoveNext() 141 buffer.Append(enumerator.Key & vbCrLf) 142 End While 143 144 txtConsole.Text = buffer.ToString() 145 End Sub ' cmdListKeys_Click 146 147 End Class ' FrmHashTableTest FrmHashTableTest.vb
23.7 Collection Classes FrmHashTableTest.vb
23.7 Collection Classes FrmHashTableTest.vb
Employee.vb 1 ' Fig. 23.31: Employee.vb 2 ' Class CEmployee for use with HashTable. 3 4 Public Class CEmployee 5 Private firstName, lastName As String 6 7 Public Sub New(ByVal first As String, ByVal last As String) 8 firstName = first 9 lastName = last 10 End Sub ' New 11 12 ' return Employee first and last names as String 13 Public Overrides Function ToString() As String 14 Return firstName & " " & lastName 15 End Function ' ToString 16 17 End Class ' CEmployee Employee.vb