问题描述
我经常看到如下代码:
int hashCode(){
return a ^ b;
}
为什么选择XOR?
这个真值表解释了为什么:
AB AND
0 0 0
0 1 0
1 0 0
1 1 1
AB
0 0 0
0 1 1
1 0 1
1 1 1
AB XOR
0 0 0
0 1 1
1 0 1
1 1 0
正如你可以看到AND和OR在混合位上做的不好。
OR平均产生3/4个1位。另一方面,平均产生3/4个空位。只有XOR具有一位与零位分布。这对散列码生成非常有价值。
请记住,对于散列码,您希望尽可能多地使用密钥信息,并获得散列值的良好分布。如果你使用AND或OR,你会得到一些数字,这些数字有很多零的数字或者有很多数字的数字。
I often see code like
int hashCode(){
return a^b;
}
Why XOR?
Of all bit-operations XOR has the best bit shuffling properties.
This truth-table explains why:
A B AND
0 0 0
0 1 0
1 0 0
1 1 1
A B OR
0 0 0
0 1 1
1 0 1
1 1 1
A B XOR
0 0 0
0 1 1
1 0 1
1 1 0
As you can see for AND and OR do a poor job at mixing bits.
OR will on average produce 3/4 one-bits. AND on the other hand will produce on average 3/4 null-bits. Only XOR has an even one-bit vs. null-bit distribution. That makes it so valuable for hash-code generation.
Remember that for a hash-code you want to use as much information of the key as possible and get a good distribution of hash-values. If you use AND or OR you'll get numbers that are biased towards either numbers with lots of zeros or numbers with lots of ones.
这篇关于为什么经常在java hashCode()中使用XOR,但是很少使用另一个按位运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!