Lab 7: Generics

The goal of this lab is to practice writing generic classes. In class we have seen examples of generic linked lists and a generic ArrayList-like class. In this lab we will write a generic class that will be something similar to a HashMap

If you need to review the premise of this lab, here's a link to the pre-lab reading.

1. Set up

As usual, make a directory for this lab. Copy the following code from the public directory.

cp /homes/tvandrun/Public/cs245/lab7/*

Open Eclipse and make a new project from the existing source in your directory.

Next, look at the driver program, SLMDriver.java, so that you see what the map will be used for. Basically it will be used to tally the frequencies of words in a file. You may remember this example from Programming I.

Finally, before you move on discuss with your partner and decide the basic structure of your classes. How will you implement the map as a linked list? What will your node classe look like? You may make your node class either as a stand-alone class or as a nested class.

2. The SortedListMap class

Now, open SortedListMap and implement it. This includes making a Node class. Notice that the constructor of SortedListMap takes a comparator. Use the comparator to determine how to add new associations to the map/list.

3. The comparator

When you are ready to test your SortedListMap, you'll also need to write a comparator. In this case, we want the key/value associations stored in alphabetical order of the keys. You will write a comparator for strings that performs that comparison. (The comparison itself is very easy, because String already has a compareTo() method which does exactly that comparison.)

However, instead of writing a plain old class that implements Comparator, practice nested classes by writing an anonymous inner class. Change the line in SLMDriver that reads

Map<String, Integer> tally = null; //new SortedListMap<String, Integer>(...your comparator...);

to

Map<String, Integer> tally = new SortedListMap<String, Integer>(...your comparator...);

except write your anonymous inner class in place of "...your comparator...".

4. To turn in

Cat and demonstrate your program in a type script, and turn in a hard copy.


Thomas VanDrunen
Last modified: Wed Feb 24 16:54:49 CST 2010