90 likes | 199 Views
Queues, Stacks, and Dictionaries. More Collections. You have been introduced to arrays and Generic.Lists , as well as the Items collections of ListBoxes and ComboBoxes . We will now introduce three more collection classes: Queues, Stacks, and Dictionaries.
E N D
More Collections • You have been introduced to arrays and Generic.Lists, as well as the Items collections of ListBoxes and ComboBoxes. • We will now introduce three more collection classes: Queues, Stacks, and Dictionaries. • Note that these are classes—to actually use them, you must create instance objects of them by calling their constructors (New).
Queues • The Generic.Queue class enables you to create a collection of objects which model First In, First Out (FIFO) behavior. • To add an item to a Queue, you don’t use Add; you use Enqueue. • Enqueue basically means “Go to the end of the line”.
Queues • To get the object that is at the front of the line, use Dequeue. • Dequeue both retrieves a reference to the object at the front of the line AND removes it from the Queue. • In the code below, the variable a will point to the object that was at the front of BankLine, and • That object (reference) will no longer be in the Queue. • See the “ListsQueuesStacksDictionaries” sample program for all of the code and a working example of a Queue.
Stacks • Stack collections model LIFO behavior: Last In, First Out. • LIFO is generally thought of as a stack of dirty dishes—the last dish brought to the sink will be the first one washed. • Stacks use “Push” to add items: • Use “Pop” to remove items (LIFO) from the stack: • See the “ListsQueuesStacksDictionaries” sample program for all of the code and a working example of a Stack.
Dictionaries • The Generic.Dictionary collection class is also very useful. • The Dictionary is like an array, in that every item in the collection has an index. • Unlike an array, however, the indices in Dictionary collections do not have to be consecutive numbers. • They can be any number, or even Strings. • These indices function just like primary keys; they provide a short code for locating items in the Dictionary.
Creating a Dictionary and Adding Items • Note that you have to define two data types for a dictionary: the type of the key (index) and the type of object the dictionary contains. • Don’t forget to actually create the Dictionary object by calling New. • Items are added using Add, which takes two parameters: the key and the object.
Retrieving Objects from a Dictionary • You retrieve items from a Dictionary by way of their keys. • In the code below, the user types in a suspected uniqname. • If the uniqname exists in the dictionary, the corresponding Student object is returned.