Difference between HashMap and IdentityHashMap

24 Mar

Most of the time I use HasMap whenever a map kinda object is needed. When reading some blog I came across IdentityHashMap in Java. It is good to understand the differences between the two because you never know when you will see them flying across your code and you trying to find out why is  this kinda Map is used here.

IdentityHashMap as name suggests uses the equality operator(==) for comparing the keys. So when you put any Key Value pair in it the Key Object is compared using == operator.

 import java.util.HashMap;
 import java.util.IdentityHashMap;
 import java.util.Map;

public class IdentityMapDemo {

public static void main(String[] args) {
 Map identityMap = new IdentityHashMap();
 Map hashMap = new HashMap();
 identityMap.put("a", 1);
 identityMap.put(new String("a"), 2);
 identityMap.put("a", 3);

hashMap.put("a", 1);
 hashMap.put(new String("a"), 2);
 hashMap.put("a", 3);

System.out.println("Identity Map KeySet Size :: " +  identityMap.keySet().size());
 System.out.println("Hash Map KeySet Size :: " + hashMap.keySet().size());

On the other hand HashMap uses equals method to determine the uniqueness of the Key.


instead of equality operator.

When you run the above code the result will be

Identity Map KeySet Size :: 2
Hash Map KeySet Size :: 1

The Keysize of Identity Map is 2 because here a and new String(“a”) are considered two different Object. The comparison is done using == operator.

For HashMap the keySize is 1 because K1.equals(K2) returns true for all three Keys and hence it keep on removing the old value and updating it with the new one.

These both Maps will behave in same manner if they are used for Keys which are user defined Object and doesn’t overrides equals method.


Posted by on March 24, 2010 in Java, Java Collections


5 responses to “Difference between HashMap and IdentityHashMap

  1. ..

    April 15, 2010 at 9:55 am

    Actually the key is created using System.identityHashCode(Object); collision is determined by using equals().

    • himanshugpt

      April 15, 2010 at 1:18 pm

      “collision is determined by using equals()” If I am not wrong then you are talking about HashMap. Right?

  2. Muneeswaran

    April 16, 2010 at 1:30 am

    Hi Gupta,
    Great post and your way of presentation is awesome.Keep it up…

  3. Muneeswaran

    April 16, 2010 at 1:31 am

    Hi Gupta,
    Nice post and your way of presentation is awesome.Keep it up.

    • himanshugpt

      April 16, 2010 at 7:33 am

      Thanks for this.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: