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

A map (also called a dictionary or associative array) associates keys with values. Here is an interface defining a generic map (we'll use this interface in our lab):

/**
 * Map.java
 * 
 * Interface to specify how an associative map
 * should work
 *
 * @author Thomas VanDrunen
 * CSCI 245, Wheaton College, Spring 2010
 * Lab 7
 * Feb 24, 2010
 */

import java.util.Iterator;

public interface Map<K, V> {
    
    /**
     * Add an association to the map.
     * @param key The key to this association
     * @param val The value to which this key is associated
     */
    void put(K key, V val);

    /**
     * Get the value for a key.
     * @param key The key whose value we're retrieving.
     * @return The value associated with this key, null if none exists
     */
    V get(K key);

    /**
     * Test if this map contains an association for this key.
     * @param key The key to test.
     * @return true if there is an association for this key, false otherwise
     */
    boolean containsKey(K key);

    /**
     * Remove the association for this key.
     * @param key The key to remove
     */
    void remove(K key);

    /**
     * Get an iterator for all the keys in this map.
     * @return An iterator over the set of keys.
     */
    Iterator<K> keyIterator();
}

Your main task in this lab is to implement this interface. On the inside, your class will be a linked list. Think about how you would implement such a think as a linked list, consider how it would need to be different to the linked lists we've already seen, and how the specific operations would be definied.

This map, however, will have a special feature. Java's HashMap orders associations in an unpredictable order--- if you iterated through the key set, you would not get the keys in the same order that you added them, nor would there be any clear reason for the order that they would be iterated through. Your map, however, will take a Comparator<K> object in its constructor---that is, a comparator with the same parameterized type as the key type. This will determine how the associations are ordered and what order the keys come when using keyIterator().

So, review the Comparator interface before lab.

Oh, and resist the temptation to refer to your class as a hash map. The "hash" in "hashmap" refers to a specific way to implement a map (or set). We are not doing hashing in this lab. But we will learn about hashing after spring break.


Thomas VanDrunen
Last modified: Wed Feb 24 16:53:44 CST 2010