java - 调试器中的 hashCode 值与 Netbeans 8.2 中的输出不同

标签 java collections hashmap

    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
     */

我的环境问题出在哪里 netbeans 8.2 jdk 1.8

最佳答案

字符串“Naveen”的实际hashCode确实是-1968696341,并且在specification之前必须始终如此。 (尽管有相反的评论)。

HashMap 实现不直接使用键的 hashCode 值。相反,它使用公式 h ^ (h >>> 16)“扩展”位,以便使用高阶位来帮助减少冲突。如果将此公式应用于字符串的 hashCode,结果为 -1968662205,它与您在调试器中看到的内容匹配。

JDK 8 代码是 here ,以及评论中的解释,为方便起见在此处引用。

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

关于java - 调试器中的 hashCode 值与 Netbeans 8.2 中的输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69426507/

相关文章:

java - 提高列表和 map 的合成速度

java - 当我的堆栈为空时无限循环

java - 在 NEO4J 中添加多个评估器

java - ArrayList 和 toString

java - 从集合类获取同步集合是否同步一个类?

java - 如何更改 HashMap 中键的值?

java - ManagedBean 上的注入(inject)服务 Spring 失败 NPE

java - 从 ini 文件读取路径,反斜杠转义字符消失?

java - 如何将多个arrayList替换为单个Collection Java

java - Android 解析 ArrayList