简体   繁体   English

hashCode 值在调试器和 output 中不相同 in.netbeans 8.2

[英]hashCode values not same in debugger and output in netbeans 8.2

    Map<String, Integer> map = new HashMap<>();
    map.put("Naveen", 100);
    System.out.println("Naveen".hashCode());
    /* output (-1968696341) so index=(-1968696341&15)=11
    but in netbeans 8.2 and jdk 1.8 debugger hashcode = -1968662205
    so the index=(-1968662205&15)=3
     */

where is the problem my enviornment is.netbeans 8.2 jdk 1.8我的环境是.netbeans 8.2 jdk 1.8 的问题在哪里

The actual hashCode of the string "Naveen" is indeed -1968696341, and it must always be so by specification (despite comments to the contrary).字符串"Naveen"的实际 hashCode 确实是 -1968696341,根据规范它必须始终如此(尽管有相反的评论)。

The HashMap implementation doesn't use the key's hashCode value directly. HashMap实现不直接使用键的 hashCode 值。 Instead, it "spreads" the bits using the formula h ^ (h >>> 16) in order to use the high-order bits to help reduce collisions.相反,它使用公式h ^ (h >>> 16) “展开”这些位,以便使用高阶位来帮助减少冲突。 If you apply this formula to the string's hashCode, the result is -1968662205 which matches what you see in the debugger.如果将此公式应用于字符串的哈希代码,结果为 -1968662205,与您在调试器中看到的相匹配。

The JDK 8 code for this is here , along with an explanation in a comment, quoted here for convenience. 此处提供了 JDK 8 代码以及评论中的解释,为方便起见在此处引用。

    /**
     * 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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM