Himanshu Gupta is currently working as a Software Engineer in India. He has been working in Java for the last 3 years. He has a BE degree from Rajasthan University. He holds SCJP-5 and SCWCD-5 Sun certifications. Himanshu has posted 5 posts at DZone. View Full User Profile

Difference between HashMap and IdentityHashMap

04.15.2010
| 27708 views |
  • submit to reddit

Most of the time I use HashMap 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.

k1.equals(k2)

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.

From http://himanshugpt.wordpress.com/2010/03/24/difference-between-hashmap-and-identityhashmap/

Published at DZone with permission of its author, Himanshu Gupta.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Witold Szczerba replied on Thu, 2010/04/15 - 5:57pm

The other difference (or a consequence) is that IdentotyHashMap does not use hash from object.hashCode() but uses System.identityHashCode(object).
This is a major difference, because you can use IdentityHashMap for mutable objects for whose hash code changes during the "in map" time frame.

Example: there is Person class with 'name' and 'age' properties and #equals checks for 'name' and 'age' and #hashCode depends on those properties as well.
Person p = new Person("Jan Kowalski");
hashMap = new HashMap();
idHashMap = new IdentityHashMap();
hashMap.put(p, something);
idHashMap.put(p, something);
p.setAge(30);
...and now what?
hashSet.containsKey(p) -> it is unknown if this is going to return true or false. Sometimes it will return true, sometimes false. This is a bug to put mutable objects into HashMap and changing them later. That will lead to hard to find bugs. On the other hand:
idHashMap.containsKey(p)
will always return true as long as this is the same object. However:
p2 = new Person("Jan Kowalski");
p2.setAge(30);
idHashMap.containsKey(p2)
will always return false.

This is important to know the difference when doing, for example, master-detail form, when some map is used to assign objects which can be modified. Using HashMap for such a case will lead to strange behavior while IdentityHashMap works fine.

Last, but not least, for big maps packed with objects with expensive #equals and #hashCode methods, IdentityHashMap will perform much better, because none of the two above methods are used.

Muneeswaran Bal... replied on Thu, 2010/04/15 - 8:24pm

Hi Guptha,

          Great post and your way of presentation is awesome.Keep it up.

Erik Clairiot replied on Fri, 2010/04/16 - 2:59am in response to: Witold Szczerba

Thanks for the post, and thanks for this comment Witold; I never thought about the danger of using mutable objects as a key map (and luckily, never encounter any problem like that, which can sure be misleading).

Himanshu Gupta replied on Fri, 2010/04/16 - 5:11am in response to: Witold Szczerba

A very good comment Witold. It is really very risky to use Mutable keys in HashMap.

Michael Bien replied on Sun, 2010/04/18 - 7:17am

calculating the hashcode from mutable attributes is not best practice anyway ;) The main reason why we have hashCode() in Object are Collections - don't break this feature. (Findbugs etc should usually emit warnings if they find mutable hashes.)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.