Lab 8: Generics

The goal of this lab is for you to practice writing generic classes. This will also give the occasion to write an anonymous inner class. Other items will be reviewed: linked structures, maps, and iterators.

In fact, this lab is really a revisiting of project 3, the homemade list map. The difference is that this time you will be making a list map (ie, a class that implements the Map ADT using a linked list) but with the following twists:

The Comparator interface

Since Comparators are something that was introduced for (almost) the first time briefly in class Tuesday, they deserve a more careful explanation here.

The other morning at breakfast my daughter was talking about how she would put the children in her class in alphabetical order by first name (Annika, Brendan, Calla, Drake...). I asked her how she would put them in order if instead she alphabetized them by the ends of their names rather than the beginnings. Since most of the girls in her class have names that end in a, that's a harder task. Then I asked her how she would sort them by the number of letters in their name. Then by height...

The point is, there can be many ways in which complex data can be sorted---or, more generally, compared. If a class implements the Comparable interface, then we need to provide exactly one way to compare two instances of that class, as coded in the compareTo() method.

What if, instead, we want to have several options for how we order the instances of a class? Then we can encode the logic of each way-of-ordering in a class that implements Comparator, that is, make "comparator" classes (and objects) to control the ordering decisions.

(The mathy explanation, for those of you with such tastes: Just as a class defines a type, and, therefore, a set, we can have several relations on that set. For those of you who have taken CSCI 243, note that a comparator defines a total order relation for that set. If any of you DMFPers ever lose sight of why all that stuff is relevant for real programming, you can read the Java API entry for Comparator and see how they use the idea of a total order to explain what the interface is supposed to mean. Ok, I'm done talking math stuff.)

As a simple example, here's a comparator that will order Strings based on their length:

class StringLengthComparator implements Comparator {
   public int compare(String o1, String o2) {
     int len1 = o1.length(),
         len2 = o2.length();
     if (len1 < len2) return -1;
     else if (len1 == len2) return 0;
     else return 1; 
   }
}
I, , read the pre-lab

Thomas VanDrunen
Last modified: Wed Feb 1 14:29:16 CST 2012