在计算对象的哈希码时,如果我们有一个类型为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/