Lab 7: Generics

1. Introduction

As mentioned in the pre-lab reading, the goal of this lab is to practice writing generic classes, and secondarily to practice writing nested classes. Many parts of this will be similar to Project 3, so the emphasis will be on what is different.

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/lab7/* .

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

Try running the JUnit tests in SLMTest.java. The tests emptyContainsKey, emptyRemove, and emptyGet should run "by luck" out of the box.

3. Details

Complete the following steps in order, making sure that the appropriate JUnit tests pass at each step.

A. The basics.

Provide a node class, instance variables, and constructor body (there already is a stub for the constructor) for the SortedListMap class. Make the node class nested within the SortedListMap class.

If you make the node class to be a static member class, then you will need to make it (explicitly) generic so that it can hold keys and values of any types. If you make it a non-static member class (RECOMMENDED), then you do not need to give the node class type parameters because it will be implicitly generic, since it will be tied to an instance of the SortedListMap class, which is generic.

Remember that the SortedListMap needs a comparator to decide the order of the keys. A comparator object like that is passed to the constructor. How should that affect SortedListMap's instance variables and constructor body?

No new JUnit tests will run after this step.

B. The comparator

In the class CompartorFactory, you'll see the stub for a static method getNormalComparator() which returns a Comparator for Strings. Fill-in this method so that it returns an anonymous inner class implementing the Comparatorinterface.

No new JUnit tests will run after this step.

C. Put

Now write the put() method in SortedListMap. This is more difficult than in Project 3 because you will have to put the new association in the right place, sorted by keys, using the comparator.

No new JUnit tests will run after this step.

D. Iterator

Now write the iterator() method, using an anonymous inner class. (This will be nearly identical to the example we saw in class yesterday, but don't look. Derive this yourself.)

The emptyIterator JUnit test should now pass.

E. ContainsKey

Now write the containsKey(). You may find it useful to use your iterator() method.

The putContainsKey JUnit test should now pass.

F. Get

Now write the get() method.

The putGet, populatedRemoveSpurious, populatedIterator, and putReplace JUnit tests should now pass.

G. Remove

Now write the remove() method.

All JUnit tests should now pass.

.
Thomas VanDrunen
Last modified: Wed Oct 15 11:52:42 CDT 2014