Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash Map entries collision

I am trying this code snippet

Map headers=new HashMap();
headers.put("X-Capillary-Relay","abcd");
headers.put("Message-ID","abcd");

Now when I do a get for either of the keys its working fine. However I am seeing a strange phenomenon on the Eclipse debugger. When I debug and go inside the Variables and check inside the table entry at first I see this

->table
--->[4]
------>key:X-Capillary-Relay
...........

However after debugging across the 2nd line I get

->table
--->[4]
------>key:Message-ID
...........

Instead of creating a new entry it overwrites on the existing key. For any other key this overwrite does not occur. The size of the map is shown 2. and the get works for both keys. So what is the reason behind this discrepancy in the eclipse debugger. Is it an eclipse problem? Or a hashing problem. The hashcode is different for the 2 keys.

like image 219
Abhiroop Sarkar Avatar asked Dec 05 '25 21:12

Abhiroop Sarkar


1 Answers

The hashCode of the keys is not used as is.

It is applied two transformations (at least based on Java 6 code):

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

and

/**
 * Returns index for hash code h.
 */
static int indexFor(int h, int length) {
    return h & (length-1);
}

Since length is the initial capacity of the HashMap (16 by default), you get 4 for both keys :

System.out.println (hash("X-Capillary-Relay".hashCode ())&(16-1));
System.out.println (hash("Message-ID".hashCode ())&(16-1));

Therefore both entries are stored in a linked list in the same bucket of the map (index 4 of the table array, as you can see in the debugger). The fact that the debugger shows only one of them doesn't mean that the other was overwritten. It means that you see the key of the first Entry of the linked list, and each new Entry is added to the head of the list.

like image 105
Eran Avatar answered Dec 08 '25 12:12

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!