Difference between HashMap and IdentityHashMap

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Java collections framework provides a type of Map called IdentityHashMap which has some weird implementation. We will see the Difference between HashMap and IdentityHashMap in this post.


Difference Between HashMap and IdentityHashMap:

Let us consider we have a Bike class and we are making below assumptions.

  • Bike has a field manufacturer which describes the manufacture of bike.
  • Bike has a field engineCapacity which is the capacity of bike’s engine.
  • hashCode() method is overridden so that it returns only engineCapacity.
  • equals() method is overridden so that bikes are equal if manufacturer and engineCapacity is equal.

Here is our Bike class.

To know the difference between HashMap and IdentityHashMap, we will simply try to write a small program to check what happens when we put some equal elements in HashMap and IdentityHashMap.

Putting Bike objects in HashMap:

Note that cbr1 and cbr2 objects are meaningfully equal and HashMap doesn’t allow duplicate keys, so it will  print the size of Hashmap as 2.

Now the difference between HashMap and IdentityHashMap lies in the object equality. IdentityHashMap actually violates the contract of object equality and it simply checks whether references are referring to same object. Let us try above program with IdentityHashMap.

This will print 3, because for IdentityHashMap, cbr1 and cbr2 are not meaningfully equal. If we refer one object using 2 references like below,

then they will qualify for equality, So the program below will output 2.

While putting elements, now, cbr1 and cbr1 are equal. I hope the article helped understand the difference between HashMap and IdentityHashMap.

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *