Removing Values
As our third main functionality, we will implement the ability to remove values from a MyHashMap based on their corresponding key.
However, before we implement the remove method, we need to create one final helper method that will simplify our implementation.
removeEntry Method
Since we are using SimpleEntry<K, V> objects to represent a key/value pair, we also want to be able to remove a SimpleEntry<K, V> object from our hashtable (the reverse of our insert helper method from Part 3).
For this, we will implement a private removeEntry helper method that takes a SimpleEntry<K, V> entry as a parameter and behaves as follows:
Gets the
keyfor theentryusing itsgetKey()method and calculates the appropriateindexas in Step 1 of thefindmethod from Part 2 of the lab.Gets the appropriate
LinkedListfrom thehashtableusing theindexcalculated in Step 1.Removes the given
entryfrom theLinkedListfound in Step 2 by using theLinkedListclass’sremove()method.
Here, we assume that the key of the given SimpleEntry<K, V> is already in the hashtable.
remove Method
In Java, removing a key/value pair is accomplished through the method:
public V remove(K key)
If the key was already in the MyHashMap, then the method returns the previous value stored for that key, else it returns null. The pseudocode for this method is:
Use the
findmethod developed above to look up whetherkeywas already in theMyHashMapIf
findreturns aSimpleEntry<K, V>object becausekeywas already in theHashMap, save the previous value from theSimpleEntry<K, V>. Then call ourremoveEntryhelper method to remove that entry from thehashtable. Next, reduce thesizeof theMyHashMapsince we removed akey. Finally, return the previousvalue.If
findinstead returnednullbecausekeywas not already in theHashMap, then we have nothing to remove and can simply returnnull.
Testing the remove Method
Do not forget to write unit tests verifying that the remove method works. It should return the correct values, actually remove key/value pairs (which can be verified using your working get method), and it should appropriately update the size of the MyHashMap.
Committing Your Progress
Don’t forget to frequently save your progress to GitHub using the add/commit/push commands with git.