为什么hash函数对hashcode做了XOR?

Why hash function has done XOR on hascode?

我看了解释,但我不明白我们通过对 hashCode 进行 XOR 来实现什么。谁能举个例子。

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

此代码取自 HashMap 源代码。我只是想知道他们为什么使用 XOR,Marko 正确地回答说 HashMap 实现使用低端位。我认为不仅是 HashMap,其他集合也会做同样的事情,这就是为什么我没有提到任何集合名称的原因。我不明白为什么人们 "rate down" 这个问题。

这是防止 "bad" 哈希码的典型策略:此类哈希码的低端位不够可变。 Java 的 HashMap 实现仅依赖于 select 存储桶的哈希码的低端位。

但是,此代码的动机早就过期了,因为 HashMap 已经进行了自己的位传播。如果在 Hashtable 上使用它会有意义,但当然自 2000 年以来编写的代码不应该使用它。

代码为openjdk java HashMap源码:HashMap.java

     /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

xor是为了让hash结果更加分散