为什么在 java hashCode() 中经常使用 XOR 而另一个位运算符很少使用? [英] Why are XOR often used in java hashCode() but another bitwise operators are used rarely?

查看:24
本文介绍了为什么在 java hashCode() 中经常使用 XOR 而另一个位运算符很少使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到这样的代码

int hashCode(){
  return a^b;
}

为什么要异或?

推荐答案

在所有位操作中,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

正如您所看到的,AND 和 OR 在混合位方面做得很差.

As you can see for AND and OR do a poor job at mixing bits.

OR 平均会产生 3/4 一位.另一方面,AND 将平均产生 3/4 个空位.只有 XOR 具有偶数一位与空位分布.这使得它对于哈希码生成非常有价值.

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.

请记住,对于散列码,您希望使用尽可能多的键信息并获得散列值的良好分布.如果您使用 AND 或 OR,您将得到偏向于带有大量零的数字或带有大量 1 的数字的数字.

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 而另一个位运算符很少使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆