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
key
for theentry
using itsgetKey()
method and calculates the appropriateindex
as in Step 1 of thefind
method from Part 2 of the lab.Gets the appropriate
LinkedList
from thehashtable
using theindex
calculated in Step 1.Removes the given
entry
from theLinkedList
found in Step 2 by using theLinkedList
class’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
find
method developed above to look up whetherkey
was already in theMyHashMap
If
find
returns aSimpleEntry<K, V>
object becausekey
was already in theHashMap
, save the previous value from theSimpleEntry<K, V>
. Then call ourremoveEntry
helper method to remove that entry from thehashtable
. Next, reduce thesize
of theMyHashMap
since we removed akey
. Finally, return the previousvalue
.If
find
instead returnednull
becausekey
was 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.