Getting Values

As our first main functionality, we will implement the ability to get values out of a MyHashMap based on their corresponding key.

However, before we implement the get method, we need to create a helper method that will also be used by several other methods (e.g., put, remove, and containsKey).

find Method

One common operation needed by the MyHashMap is looking up the SimpleEntry<K, V> currently stored in the hashtable for a given key. For this, we will implement a private find helper method that searches the hashtable for a SimpleEntry<K, V>. This method should:

  1. Calculate the hash code for key using Java’s key.hashCode() method, then convert that hash code into an index by using the modulus operator and the length of the hashtable.

Hint

Because Java’s hashCode() method can return negative numbers, we need to convert the hash code to a positive number, which can be done quickly with the following code:

int hash = key.hashCode() & Integer.MAX_VALUE;

Then we can find the appropriate index with the modulus operator.

  1. Get the appropriate LinkedList from the hashtable using the index calculated in Step 1.

  2. Iterate through every SimpleEntry<K, V> in the LinkedList found in Step 2, looking for one whose getKey() is equal() to key. If one is found, return that SimpleEntry<K, V>.

  3. If we do not find a matching SimpleEntry<K, V> in Step 3, return null to signify that key is not already stored in the MyHashMap.

get Method

The get method can then rely on the find method to find the corresponding value for a given key. In particular, implement a public method called get that takes a single K key parameter. The get method should return the V value stored in the MyHashMap for that key if it has a SimpleEntry<K, V>, otherwise it should return null.

Testing Our Progress

Unfortunately, we cannot test our get method until we have the ability to put data into the MyHashMap, which we will implement in the next part of the lab.

Once we have implemented put, you should write unit tests to verify that your get method is implemented correctly. Suggested tests include:

  1. Insert a key/value pair, then call get to make sure the correct value is returned
  2. Insert a new value for a key that already exists in the MyHashMap, then call get to make sure the newest value is returned
  3. Call get for a key that has not be inserted and verify that null is returned

Hint

Remember the Debugger in Visual Studio Code, which will allow you to inspect the values of variables as you debug your unit tests.

Committing Your Progress

Don’t forget to frequently save your progress to GitHub using the add/commit/push commands with git.