java - 计算hashCode时转换数据类型

标签 java hash dictionary bit-manipulation hashcode

在计算对象的哈希码时,如果我们有一个类型为long的属性,那么我们可以通过以下方法将其转换为int:

 1. int k = (int) (l);
 2. int k = (int)(l^(l>>>32));
( l is an attribute of the object whose datatype is long)

建议(《Effective Java》中的 Joshua bloch)使用第二种方法。这背后的原因是什么?我的想法如下,请您提供意见,我的主张是否正确?

如果还有什么可以补充的。谢谢。

最佳答案

建议使用第二种方法,因为它可以很好地分配位的选择,因为它比仅考虑低 32 位的第一种方法更多地考虑高 32 位和低 32 位。

l >>> 32 :: is dismissing the lower 32 bits or selecting higher 32 bits.

l ^ (l>>>32) :: is XORing higher 32 bits to lower 32 bits which gives you more distribution in-terms of selecting the overall bits than just taking lower 32 bits which the first method does.

关于java - 计算hashCode时转换数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18800458/

相关文章:

java - 我如何将 boolean 值传递给新对象?

java - 无论 num1、num2 或 num3 输入什么,总分始终等于 0.0

c++ - 计算哈希插入的运行时间?

php - 密码哈希 API 查询

安卓。 Facebook 登录的 key 哈希

Python - 将字典列表重新组合为两个嵌套的字典列表?

Python-替换字典中键、值中的特殊字符

java - 如何从 GSON 更改扩展类中属性的 @SerializedName

java - 以类实例/对象作为参数的类方法

arrays - 在字典上调用 .sort 会创建新类型吗?