wood burning stoves 2.0*
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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Hash function in HashMap method" Watch "Hash function in HashMap method" New topic
Author

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


Regards
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
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

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


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
wood burning stoves
 
subject: Hash function in HashMap method