CHAPTER 9 COLLECTIONS AND GENERICS
Here, you insert three items into the Queue class using its Enqueue() method. The call to Peek()
allows you to view (but not remove) the first item currently in the Queue. Finally, the call to Dequeue()
removes the item from the line and sends it into the GetCoffee() helper function for processing. Note
that if you attempt to remove items from an empty queue, a runtime exception is thrown. Here is the
output you receive when calling this method:
***** Fun with Generic Collections *****
Homer is first in line!
Homer got coffee!
Marge got coffee!
Lisa got coffee!
Error! Queue empty.
Working with the SortedSet Class
The SortedSet class is useful because it automatically ensures that the items in the set are sorted
when you insert or remove items. However, you do need to inform the SortedSet class exactly how
you want it to sort the objects, by passing in as a constructor argument an object that implements the
generic IComparer interface.
Begin by creating a brand new class named SortPeopleByAge, which implements IComparer,
where T is of type Person. Recall that this interface defines a single method named Compare(), where you
can author whatever logic you require for the comparison. Here is a simple implementation of this class:
class SortPeopleByAge : IComparer
{
public int Compare(Person firstPerson, Person secondPerson)
{
if (firstPerson.Age > secondPerson.Age)
return 1;
if (firstPerson.Age < secondPerson.Age)
return -1;
else
return 0;
}
}
Now update your Program class with the following new method, which I assume you will call from
Main():
static void UseSortedSet()
{
// Make some people with different ages.
SortedSet setOfPeople = new SortedSet(new SortPeopleByAge())
{
new Person {FirstName= "Homer", LastName="Simpson", Age=47},
new Person {FirstName= "Marge", LastName="Simpson", Age=45},
new Person {FirstName= "Lisa", LastName="Simpson", Age=9},
new Person {FirstName= "Bart", LastName="Simpson", Age=8}
};
345