理解方法注释java 8中HashMap类的hash()方法

Ram*_*mar 10 java hash hashmap data-structures

 /**
     * 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);
}
Run Code Online (Sandbox Code Playgroud)

下面是JDK 1.6的早期版本

/**
     * Applies a supplemental hash function to a given hashCode, which
     * defends against poor quality hash functions.  This is critical
     * because HashMap uses power-of-two length hash tables, that
     * otherwise encounter collisions for hashCodes that do not differ
     * in lower bits. Note: Null keys always map to hash 0, thus index 0.
     */
    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下这种哈希的好处,而不是早期版本的java中所做的那样.这将如何影响密钥分发的速度和质量,我指的是在jdk 8中实现的新哈希函数以及如何通过它来减少冲突?

Old*_*eon 3

在方法表现相当糟糕的情况下,hashCode性能HashMap可能会急剧下降。例如,假设您的hashCode方法仅生成一个16位数。

xor这通过将哈希码自身右移来解决这个问题16。如果在此之前该数字分布良好,那么现在应该仍然如此。如果它很糟糕,这应该会改善它。