Lab 9: Generics

1. Introduction

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.

A map (also called a dictionary or associative array) associates keys with values. See the Map in Java's API as an example of the functionality.

We will use a simplified version of this interface in the lab. Your main task in this lab is to implement this interface.

2. Set up

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

cp -r /homes/tvandrun/Public/cs245/lab9/* .

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.

3. Details

See the pre-lab reading to review the details if necessary. THe important thing is before you move on to 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 class look like? Make your node class nested in the SortedListMap class.

4. The SortedListMap class

Now, open SortedListMap. It is currently just a stub. You can use Eclipse's feature to "add unimplemented methods" (hover over the error icon to the left of the line with the class declaration) to make stubs for the rest of the methods in the Map interface.

I recommend you write the part of this class in the following order:

5. 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, make this also to be an anonymous inner class.

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...".


Thomas VanDrunen
Last modified: Thu Mar 20 11:16:20 CDT 2014