File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Hash function in HashMap method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Hash function in HashMap method" Watch "Hash function in HashMap method" New topic

Hash function in HashMap method

Salil Vverma
Ranch Hand

Joined: Sep 06, 2009
Posts: 255

Can any one suggest,what exactly are we trying to achieve out of this function in java.util.HashMap and why it was implemented this way?

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);

Salil Verma
Sunny Bhandari
Ranch Hand

Joined: Dec 06, 2010
Posts: 448

Hi Salil,

Good question. This function is called by put and get of HashMap class:

See the javadocs for more clarity:
* 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.

This function is acting as extra processing for hash code so as to reduce the collisions. (Trying 8 to be maximum for a given hashcode)

Hope that helps.

But you can ignore while preparing for exams. There will be so many such functions in various classes ....

Java Experience
Ankit Garg

Joined: Aug 03, 2008
Posts: 9462

This code also uses shift operators which are not on the exam...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
I agree. Here's the link:
subject: Hash function in HashMap method
It's not a secret anymore!