193k views
5 votes
You’ll be implementing a hashtable class called MyHashtable. It implements the interface DictionaryInterface.

The hashtable you’ll be making will use Strings as the keys and Object as the values. Similar to linked lists, by storing Object as values, you can store any kind of object in the hashtable.

To implement a hashtable:

Use a protected inner class inside MyHashtable called Entry. This inner class stores Key/Value pairs. So it has two fields:

String key

Object value

It also should have a constructor for initializing the key and value.

Your hashtable will define three protected fields (remember that protected means that the field can only be accessed from within the class or by any child class of the class).

int tableSize - the size of the array being used by the hashtable

int size- the number of key/value entries stored in the hashtable

MyLinkedList[] table - an array of MyLinkedList. The reason that each element of the array is a linked list is to store multiple entries which collide, that is, for which the hash for the different keys is the same index in the table.

User GaloisGirl
by
8.6k points

1 Answer

4 votes

Final answer:

To construct a MyHashtable class as part of the DictionaryInterface, you implement an inner Entry class for Key/Value pairs and protect fields for the table size, number of entries, and an array of MyLinkedLists for handling hash collisions.

Step-by-step explanation:

To implement a hashtable in Java, especially the MyHashtable class that adheres to the DictionaryInterface, you will need an inner class to represent the Key/Value pairs and an array to hash and store these pairs in conjunction with linked lists to handle collisions. Let's define the inner class Entry first:

protected class Entry {
String key;
Object value;

protected Entry(String key, Object value) {
this.key = key;
this.value = value;
}
}

Next, we define the protected fields for the hashtable:

protected int tableSize;
// Defines the size of the hashtable array

protected int size;
// Tracks the number of key/value pairs in the hashtable

protected MyLinkedList[] table;
// An array where each element is a linked list to handle collisions

It is essential to choose a good hashing function to distribute keys uniformly across the array. When the hash function produces the same index for multiple keys, these keys are stored in the same linked list, thus handling collisions.

User Factory Girl
by
7.8k points