Generic Classes

 

Goals

Overview


Demo: A Generic Pair Class

We will work with a Pair class. A Pair can hold a pair of any two things of the same (non-primitive) type. For example, we can create a Pair of Strings, or a Pair of Widgets.

Exercise #1: A Generic Triplet Class

Create a generic class called Triplet which is similar to pair except that it holds three things. Instead of a swap() method, the Triplet class should have the method shiftLeft() that behaves as shown below. Download TripletTest.java to test it.
> java TripletTest
Before shiftLeft():
[hello, there, world]
After shiftLeft():
[there, world, hello]

Before shiftLeft():
[25, 50, 100]
After shiftLeft():
[50, 100, 25]

Exercise #2 (Challenge Problem): A Generic Dictionary Class

Here we work with a dictionary that contains (key, value) pairs. Download: Compile the files. Run the DictTest test program (java DictTest), which should print
harry
16

The supplied Dict class stores just one value for every key, regardless of how many entries with a given key are added. Leaving the Entry class as-is, modify the Dict class so that for each key it stores a List of values, which the lookup method returns. Download DictSltnTest.java. It should produce the following output:

> java DictSltnTest
harry
hermoine
ron
16
17
15