Lab 8: Writing generic classes

The goal of this lab is to practice writing generic classes.

1. Introduction

In addition to the Comparator class, which can be used to decide an ordering for objects in a class, the Java Collections Framework also contains a Comparable interface, which requires that a class implement a method, compareTo(), to compare it with another object of the same class. The part about "the same" class must be implemented with generics. Study the Comparable interface in the Java API.

You will write a generic linked list class which will sort items as they are entered into the list.

2. Setup

Copy the following files from the course public directory:

cp /homeemp/tvandrun/pub/245/List.java .
cp /homeemp/tvandrun/pub/245/ListDriver.java.

3. Specification

The ListDriver program (once all of its parts are uncommented) creates three lists-- a list of Strings, a list of Integers, and a list of a class StringWrapper, which you will have to write. For each String in the file, it will enter the String, its size, and a wrapper based on the String into the respective lists. Finally, it prints the contents of each list. Since the lists should sort their items as they are entered, the output should be, first, the Strings alphabetized; then the sizes, in increasing number, then the Strings from shortest to longest.

Thus, the StringWrapper class must implement the Comparable interface, and it must compares Strings based on their length.

4. The SortList class

Write a class SortList. It needs to implement the List interface I've given you, but in addition, its type parameter much implement the comparable type. Implement the list so that when a new item is added, it is put in the order specified by compareTo(). Depending on how you implement the List class, you will probably also need to implement a class for the nodes (also generic).

The method iterator() will require some more work. It needs to return an object which implements the Iterator interface and iterates over the contents of the list. You will need to write another class, also generic, to be an iterator class for this list. Consult the Iterator interface in the Java API for help on this.

Then compile and test ListDriver.

When you are confident it works right, uncomment the part that uses the List class as an integer list. It should just work, without any modifications.

5. The StringWrapper class

Now write a class StringWrapper. It must

Then uncomment the parts in the driver that use StringWrapper and test.


Thomas VanDrunen
Last modified: Thu Mar 1 13:06:26 CST 2007