简体   繁体   English

关于执行 Java HashMap

[英]About the implementation of Java HashMap

Why the capacity must be a multiple or 2?为什么容量必须是倍数或2? Why use "&" in the indexFor functions?为什么在 indexFor 函数中使用“&”? Why recompute the hash in the hash function instead of directly using the key's hash code?为什么要重新计算 hash function 中的 hash 而不是直接使用密钥的 hash 编码?

I think there are some important differences between the this implementation and the description on the "Introduction to Algorithm".我认为这个实现和“算法简介”中的描述有一些重要的区别。

What does ">>>" mean? “>>>”是什么意思?

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

Can anyone give me some guide?谁能给我一些指导? I appreciate If some one can explain the hash algorithm.我很感激如果有人能解释 hash 算法。 Thanks a lot!非常感谢!

This is a performance optimization.这是一个性能优化。 The usual way to map a hash code to a table index is map hash 代码到表索引的通常方法是

table_index = hash_code % table_length;

The % operator is expensive. %运算符很昂贵。 If table_length is a power of 2, then the calculation:如果table_length是2的幂,那么计算:

table_index = hash_code & (table_length - 1);

is equivalent to the (much) more expensive modulo operation.相当于(多)更昂贵的模运算。

Pay no attention to the man behind the curtain.不要注意窗帘后面的那个人。

The actual algorithm is no doubt a combination of "what feels good" to the developer, fixes for some odd degenerate cases, and simple tradition (for which users often develop obscure dependencies).实际的算法无疑是开发人员“感觉良好”的组合,对一些奇怪的退化情况的修复,以及简单的传统(用户经常为此开发模糊的依赖关系)。

And note this:并注意这一点:

 * 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.

Net: So long as it works and the performance is good, you don't care.网:只要能用,性能好,你无所谓。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM