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:
- Calculate the hash code for
key
using Java’skey.hashCode()
method, then convert that hash code into anindex
by using the modulus operator and the length of thehashtable
.
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.
Get the appropriate
LinkedList
from thehashtable
using theindex
calculated in Step 1.Iterate through every
SimpleEntry<K, V>
in theLinkedList
found in Step 2, looking for one whosegetKey()
equals()
key
. If one is found, return thatSimpleEntry<K, V>
.If we do not find a matching
SimpleEntry<K, V>
in Step 3, returnnull
to signify thatkey
is not already stored in theMyHashMap
.
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:
- Insert a
key/value
pair, then callget
to make sure the correctvalue
is returned - Insert a new
value
for akey
that already exists in theMyHashMap
, then callget
to make sure the newestvalue
is returned - Call
get
for akey
that has not be inserted and verify thatnull
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.