I have been studying the internals of the Hashmap implementation.
For adding or getting value from map based on the key, it will calculate hashcode and then it finds bucket location (or table location/index, correct me if I am wrong).
But it is calculating the hash-code twice.
In the below code snippet, key.hashcode() is native method in object class and then hash method is implemented in the same class.
It is given in the comments of the hash method that why it is being calculated twice, which i could not understand.
Can any one please explain it briefly with a scenario?
int hash = hash(key.hashCode());
/ * Applies a supplemental hash function to a given hashCode, which
* defends against poor quality hash functions. This is critical
* because HashMap uses power-of-two length hash tables, that
* otherwise encounter collisions for hashCodes that do not differ
* in lower bits. Note: Null keys always map to hash 0, thus index 0.
*/
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
Thanks.