In this exercise you will learn to use library data structures and also increase your "object" skills. The desired outcome is a hashtable that can store duplicates.
Recall the problem with Java's Hashtable: duplicates may
not be stored. For example, consider:
Hashtable h = new Hashtable ();
h.put ("A", "AAA"); // Store the key "A" and value "AAA"
h.put ("B", "BBB"); // Store the key "B" and value "BBB"
h.put ("B", "BBBBB"); // This key-value pair replaces "B" and "BBB".
What we would like is a hashtable that stores duplicates. However,
suppose we have a hashtable DupHashtable that stores
duplicates, e.g.
DupHashtable h = new DupHashtable ();
h.put ("A", "AAA"); // Store the key "A" and value "AAA"
h.put ("B", "BBB"); // Store the key "B" and value "BBB"
h.put ("B", "BBBBB"); // Store the value "BBBBB" with existing key "B"
When we retrieve on a key, we could have a collection of values stored
along with that one key. Thus, in retrieving, we need to be prepared
to receive a collection of values. In other words, the equivalent
in DupHashtable of the get() method in
Hashtable should return a collection.
In this exercise, you are to implement the class DupHashtable and compare its performance with that of Hashtable:
public class DupHashtable implements Enumeration {
// Put a key-value combination into the table.
public void put (Object key, Object value)
{
}
// Given a key, return the (zero, one or many) values
// associated with the key.
public LinkedList get (Object key)
{
}
// Return the number of values stored.
public int size ()
{
}
// Return an Enumeration of values in the hashtable.
// This interface is to be implemented by DupHashtable itself.
public Enumeration allValues ()
{
}
// One of the two methods in the Enumeration interface.
public boolean hasMoreElements ()
{
}
// One of the two methods in the Enumeration interface.
public Object nextElement ()
{
}
// Some testing ...
public static void main (String[] argv)
{
// Test 1:
DupHashtable dup = new DupHashtable ();
dup.put ("A", "AAA");
printTable (dup);
// Test 2:
dup = new DupHashtable ();
dup.put ("A", "AAA");
dup.put ("B", "BBB");
dup.put ("C", "CCC");
printTable (dup);
// Test 3:
dup = new DupHashtable ();
dup.put ("A", "AAA");
dup.put ("B", "BBB");
dup.put ("C", "CCC");
dup.put ("A", "AAAAA");
dup.put ("C", "CCCCC");
printTable (dup);
}
public static void printTable (DupHashtable dup)
{
System.out.println ("Hashtable with " + dup.size() + " values: ");
Enumeration e = dup.allValues ();
while (e.hasMoreElements()) {
System.out.println (e.nextElement());
}
}
}
There is also a main method with some tests.
Hashtable with 1 values: AAA Hashtable with 3 values: AAA CCC BBB Hashtable with 5 values: AAA AAAAA CCC CCCCC BBB
Submission: