【发布时间】:2011-01-25 17:26:45
【问题描述】:
有人可以向我解释一下静态 HashMap#hash(int) 方法吗?
生成均匀分布的哈希的理由是什么?
/**
* 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);
}
举个例子会更容易理解。
澄清 我知道运算符、真值表和按位运算。我真的无法真正解码实现,也无法真正解码评论。甚至是背后的原因。