How do you find the right key when keys share a bucket?
Testing keys in order
Elena Ruiz
How a hash table finds a value
After a mismatch, follow the next link until you find a match or reach the end.
Transcript
You're looking for 5, so you start at the oak entry. This chain holds 2 keys, and you need to tell them apart.
Bucket 1 narrows down where you need to look, but both keys belong here. In this table of 4 buckets, each key is its own hash code, the number you use to work out which bucket to look in. So the hash code for the oak entry is 1, and the hash code for the ash entry is 5. Look at how many groups of 4 fit: 1 is 0 groups of 4 plus 1, and 5 is 1 group of 4 plus 1. It's the leftover number that tells you where to look, so that last 1 puts both keys in bucket 1. When different keys land in the same bucket like this, you've got a collision. Notice that this collision happens even though the codes are different.
Now put the bucket numbers aside and compare the 1 in the oak entry with the 5 you're looking for. Since 1 isn't equal to 5, skip the oak entry and follow the next link to the ash entry. Sharing a bucket isn't enough because what matters is key equality, the rule for deciding whether the stored key and the key you want count as the same key. For these keys, key equality means the numbers themselves must be equal.
Now look at the ash entry: 5 equals 5, so you've got a match. You can stop here because this pair has the very key you asked for.
But suppose the ash entry weren't there and the oak entry had a link to the end instead, with an end marker telling you there's nothing left to test. Then 5 would be missing because it would have to be in bucket 1, and you've checked every key there. So start with the bucket it belongs in and follow the links in order after each mismatch until you find the key or reach the end without it.