【问题标题】:hashCode values not same in debugger and output in netbeans 8.2调试器中的 hashCode 值与 netbeans 8.2 中的输出不同
【发布时间】:2021-11-24 07:39:54
【问题描述】:
    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[enter image description here][1]
     */

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

调试器 && 控制台

https://i.stack.imgur.com/3EHHs.png

【问题讨论】:

  • 它对我有用。我在调试器中看到与屏幕上打印的相同的哈希码。我认为您可能错误地解释了调试器输出。试试int hash = "Naveen".hashCode(); 用调试器看代码,应该会看到正确的值。
  • @markspace 我试过 int hash = "Naveen".hashCode();但我得到了相同的结果
  • @user16320675 字符串的 hashCode 是 specified 可重复。

标签: java collections hashmap


【解决方案1】:

字符串"Naveen"的实际hashCode确实是-1968696341,而且specification一定总是这样(尽管cmets相反)。

HashMap 实现不直接使用键的 hashCode 值。相反,它使用公式h ^ (h &gt;&gt;&gt; 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);
    }

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 2018-12-10
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2017-04-02
    相关资源
    最近更新 更多