有效Java hashCode()实现中的位移

Mar*_*ope 20 java hashcode

我想知道是否有人可以详细解释什么

(int)(l ^ (l >>> 32));

在下面的hashcode实现中(由eclipse生成,但与Effective Java相同):

private int i;
private char c; 
private boolean b;
private short s;
private long l;
private double d;
private float f;

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + i;
    result = prime * result + s;
    result = prime * result + (b ? 1231 : 1237);
    result = prime * result + c;
    long t = Double.doubleToLongBits(d);
    result = prime * result + (int) (t ^ (t >>> 32));
    result = prime * result + Float.floatToIntBits(f);
    result = prime * result + (int) (l ^ (l >>> 32));
    return result;
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jon*_*eet 32

基本上,它将底部32位的X字段排在前32位.这是一个爆炸版本:

// Unsigned shift by 32 bits, so top 32 bits of topBits will be 0,
// bottom 32 bits of topBits will be the top 32 bits of l
long topBits = l >>> 32;

// XOR topBits with l; the top 32 bits will effectively be left
// alone, but that doesn't matter because of the next step. The
// bottom 32 bits will be the XOR of the top and bottom 32 bits of l
long xor = l ^ topBits;

// Convert the long to an int - this basically ditches the top 32 bits
int hash = (int) xor;
Run Code Online (Sandbox Code Playgroud)

要回答你的评论:你有一个long值,必须转换成一个int作为哈希的一部分(结果必须只有32位).你打算怎么做?您可以采用最低32位 - 但这意味着只会忽略前32位的更改,这不会使它成为一个非常好的哈希.这样,单个输入位的改变总是导致散列的单个位的改变.诚然,你仍然可以得到碰撞容易-改变 7位和第39,例如,或任何其他对位相距32个位置的-但是这必然是这样的,因为你是从2个去64可能值2 32.


cor*_*iKa 8

它需要一个64位的数字,将它分成两半,然后将两半(基本上)相加.