CHAPTER 9 COLLECTIONS AND GENERICS
// Now look at the top item, pop it, and look again.
Console.WriteLine("First person is: {0}", stackOfPeople.Peek());
Console.WriteLine("Popped off {0}", stackOfPeople.Pop());
Console.WriteLine("\nFirst person is: {0}", stackOfPeople.Peek());
Console. WriteLine("Popped off {0}", stackOfPeople.Pop());
Console.WriteLine("\nFirst person item is: {0}", stackOfPeople.Peek());
Console.WriteLine("Popped off {0}", stackOfPeople.Pop());
try
{
Console.WriteLine("\nnFirst person is: {0}", stackOfPeople.Peek());
Console.WriteLine("Popped off {0}", stackOfPeople.Pop());
}
catch (InvalidOperationException ex)
{
Console.WriteLine("\nError! {0}", ex.Message);
}
}
Here, you build a stack that contains three people, added in the order of their first names: Homer,
Marge, and Lisa. As you peek into the stack, you will always see the object at the top first; therefore, the
first call to Peek() reveals the third Person object. After a series of Pop() and Peek() calls, the stack
eventually empties, at which time additional Peek() and Pop() calls raise a system exception. You can
see the output for this here:
***** Fun with Generic Collections *****
First person is: Name: Lisa Simpson, Age: 9
Popped off Name: Lisa Simpson, Age: 9
First person is: Name: Marge Simpson, Age: 45
Popped off Name: Marge Simpson, Age: 45
First person item is: Name: Homer Simpson, Age: 47
Popped off Name: Homer Simpson, Age: 47
Error! Stack empty.
Working with the Queue Class
Queues are containers that ensure items are accessed in a first-in, first-out manner. Sadly, we humans
are subject to queues all day long: lines at the bank, lines at the movie theater, and lines at the morning
coffeehouse. When you need to model a scenario in which items are handled on a first-come, firstserved basis, you will find the Queue class fits the bill. In addition to the functionality provided by the
supported interfaces, Queue defines the key members shown in Table 9-6.
343