Why does lookup give the same hash code?
Why hash codes repeat
Elena Ruiz
How a hash table finds a value
Lookup gives H(5) = 5 again: 5 is the same hash code, not a table position.
Transcript
The storage key is 5. It goes into the rule now, and when you look it up later, you'll need to get the same number back.
Notice the storage key, 5, because once you know the key and the rule, the answer lookup needs is already fixed. Look at the storage line: this rule gives back exactly what went in, so the result is 5. A hash function is a rule that takes a key and gives you an integer. This particular hash function leaves your number unchanged. That 5 after the equals sign is the hash code, the integer you get back for the key. So the hash code for 5 at storage is 5. Giving you back the very number you put in is what makes this the identity rule. The identity rule works this way for every integer key. We write k for whichever key you put in. On the storage line, k is 5. Now H of k stands for the code you get back for that key. Here H of k equals k, so the storage line reads H of 5 equals 5.
Now suppose the key you're looking for is 5. Follow the lookup line: you apply the same identity rule, so H of 5 equals 5 again. You get matching codes because the rule depends only on the key, and whether you're storing or finding, the key hasn't changed.
Now look at the 4 table positions and read their numbers: 0, 1, 2 and 3. None of the table positions is numbered 5, but 5 is still the right hash code because it's what the rule gives back. So when you look up the same key, using the same rule gets you the same code, even if that code isn't a position in the table.