'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



Solution 1:[1]

The actual hashCode of the string "Naveen" is indeed -1968696341, and it must always be so by specification (despite comments to the contrary).

The HashMap implementation doesn't use the key's hashCode value directly. Instead, it "spreads" the bits using the formula h ^ (h >>> 16) in order to use the high-order bits to help reduce collisions. If you apply this formula to the string's hashCode, the result is -1968662205 which matches what you see in the debugger.

The JDK 8 code for this is here, along with an explanation in a comment, quoted here for convenience.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Stuart Marks