![]() | |||||||||||||||||||||
![]() |
|
|
Adding to the collection
Let’s say we want to stock our vending machine. Obviously, if there is no product we can’t make any money, and we want to make money. Let’s say for now that we want to add a simple chocolate bar. We will get into different kinds of candy bars, and thus different objects later.
We first set candybar1 to be an object of type clscandybar We then add that candybar to the collection. That’s all there is to it, VendingMachine is now stocked with one chocolate coconut candybar. Of course, being that we like various types of candy bars we need to stock various types of candy bars, that is why we set the properties associated with the object. Let’s now stock some hot tamales.
Our vending machine now contains two candy bar types. We can display the candybars by referencing the position value. For instance:
When run in the program would produce a Message Box that displays “Almond Joy”.
If we decided to stock many more candy bars it may be somewhat difficult to know how where in the collection these objects existed unless we kept track of them. Since we want to be able to get at these candybars at anytime without going throughout the entire machine we should add a key when adding the item.
For instance, when adding the first candybar, the Almond Joy, we should add it like this:
The second argument is the key value which can be any string. Now when we want to reference information related to this object in the collection all we need to do is pass the key value where we passed the position before. If we wanted to create a Message Box that displayed the Filling of the Almond Joy bar we would simply pass this statement.
Now perhaps, we want to know how many candybars are in the vending machine. We could view the value of the count property.
We can progress through all the objects in the collection by using a “for each” loop. We do not need to set up a special counter or reference since there is a method known as the _NewEnum method. This method is never referenced since it is a hidden method.
This creates message boxes that display the main type of candy bar, the filling and the name of the candy bar.
Removing Items
Lets say that you wish to buy a candy bar from the vending machine. You decided that today you feel like an Almond Joy candy bar. You therefore need to remove the item from the vending machine collection since it is no longer there. You can do this by either referencing the index number or the key.
Index Number:
Key:
Now, the item is deleted from the collection, and the Hot Tamales becomes index number 1. This is one example of the importance of keeping track the index number of objects if that is how you decide to reference items in collections.
|
Section 2: Creating a Collection
| ||||||||||||
Counter