【发布时间】:2015-08-21 19:59:32
【问题描述】:
我一直在研究Hashmap 实现的内部结构。
对于基于键从映射中添加或获取值,它将计算哈希码,然后找到存储桶位置(或表位置/索引,如果我错了,请纠正我)。
但它计算了两次哈希码。
在下面的代码sn-p中,key.hashcode()是对象类中的native方法,然后hash方法在同一个类中实现。
在 hash 方法的 cmets 中给出了为什么要计算两次,我无法理解。
谁能用一个场景简单解释一下?
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);
}
谢谢。
【问题讨论】:
标签: java