Created
March 26, 2011 21:32
-
-
Save fabiokung/888655 to your computer and use it in GitHub Desktop.
snippet of HashMap's default implementation, from Sun's JVM (Mac OSX build 1.6.0_24-b07-334-10M3326)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
/** | |
* Returns index for hash code h. | |
*/ | |
static int indexFor(int h, int length) { | |
return h & (length-1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment