简体   繁体   English

为什么 AND(&) 运算符用于计算 Hashmap 中的最终索引 为什么不用 modulo(%) 运算符,即 hashValue & ()

[英]Why AND(&) operator used calculating final index in Hashmap why not modulo(%) operator i.e hashValue & ()

I am trying to understand HashMap implementation.我正在尝试了解 HashMap 的实现。 I found after calculating key hash value, final hash value is generated using AND operator (hashValue & (n-1)) where n is size of bucket.Could someone explain why modulo is not used which will also guarantee output range within bucket size.我发现在计算键哈希值后,最终的哈希值是使用 AND 运算符生成的 (hashValue & (n-1)),其中 n 是存储桶的大小。有人可以解释为什么不使用模数,这也将保证存储桶大小内的输出范围。

& runs faster, in exchange for working only for powers of two. &运行速度更快,换取只为 2 的幂工作。 (Specifically, x & (n - 1) == x % n if x is nonnegative and n is a power of two. x & (n - 1) also does what you want for a hash table -- even if x is negative, x & (n - 1) isn't -- unlike x % n .) (具体来说,如果x为非负且n是 2 的幂,则x & (n - 1) == x % n n。x x & (n - 1)也可以为哈希表执行您想要的操作——即使x为负, x & (n - 1)不是——不像x % n 。)

That's the complete and only reason.这就是完整且唯一的原因。

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

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