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.
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 the entry
using its getKey()
method and calculates the appropriate index
as in Step 1 of the find
method from Part 2 of the lab.
Gets the appropriate LinkedList
from the hashtable
using the index
calculated in Step 1.
Removes the given entry
from the LinkedList
found in Step 2 by using the LinkedList
class’s remove()
method.
Here, we assume that the key
of the given SimpleEntry<K, V>
is already in the hashtable
.
In Java, inserting a 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 whether key
was already in the MyHashMap
If find
returns a SimpleEntry<K, V>
object because key
was already in the HashMap
, save the previous value from the SimpleEntry<K, V>
. Then call our removeEntry
helper method to remove that entry from the hashtable
. Next, reduce the size
of the MyHashMap
since we removed a key
. Finally, return the previous value
.
If find
instead returned null
because key
was not already in the HashMap
, then we have nothing to remove and can simply return null
.
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
.
Don’t forget to frequently save your progress to GitHub using the add
/commit
/push
commands with git.