The HashMap
class maps keys to values by running the hashCode
of the key through a hash function. The hash function is used to create an index into an array of buckets. For example, a very primitive hash function would be hashCode % tableSize
. Changing the key's hashCode
would alter the index created by the hash function, meaning there is nothing to be found in that bucket.
Let's run an example, assuming that the initial hashCode
is 15 and the table size is 4:
┌----------------------┐
15 (initial hashCode) -> | hashCode % tableSize | -> index 3
| (hash function) |
└----------------------┘
So let's insert the value at index 3:
┌------┐
0 | null |
|------|
1 | null |
|------|
2 | null |
|------|
3 | key! | <- insert
└------┘
Now let's modifiy the key's hashCode
so that it is now 13:
┌----------------------┐
13 (modified hashCode) -> | hashCode % tableSize | -> index 1
| (hash function) |
└----------------------┘
What's at index 1? Nothing, null
.
A lot of things have been simplified here. In a real hash table implementation, the hash function is much more complex to create a more even distribution. Also, the buckets are linked-lists so collisions can be handled.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…