Collision resolution in Java HashMap

user2938723 picture user2938723 · Oct 30, 2013 · Viewed 109.3k times · Source

Java HashMap uses put method to insert the K/V pair in HashMap. Lets say I have used put method and now HashMap<Integer, Integer> has one entry with key as 10 and value as 17.

If I insert 10,20 in this HashMap it simply replaces the the previous entry with this entry due to collision because of same key 10.

If the key collides HashMap replaces the old K/V pair with the new K/V pair.

So my question is when does the HashMap use Chaining collision resolution technique?

Why it did not form a linkedlist with key as 10 and value as 17,20?

Answer

Sanjay T. Sharma picture Sanjay T. Sharma · Oct 30, 2013

When you insert the pair (10, 17) and then (10, 20), there is technically no collision involved. You are just replacing the old value with the new value for a given key 10 (since in both cases, 10 is equal to 10 and also the hash code for 10 is always 10).

Collision happens when multiple keys hash to the same bucket. In that case, you need to make sure that you can distinguish between those keys. Chaining collision resolution is one of those techniques which is used for this.

As an example, let's suppose that two strings "abra ka dabra" and "wave my wand" yield hash codes 100 and 200 respectively. Assuming the total array size is 10, both of them end up in the same bucket (100 % 10 and 200 % 10). Chaining ensures that whenever you do map.get( "abra ka dabra" );, you end up with the correct value associated with the key. In the case of hash map in Java, this is done by using the equals method.