Menu
Topics Index
...
`


Collections Framework > Map Classes >
Siva Nookala - 15 Apr 2016
IdentityHashMap is similar to HashMap except for the following differences:
1) In case of HashMap, JVM will always use equals() method to identify duplicate keys.
2) In case of IdentityHashMap, as its name suggests, JVM will always use == operator to identify duplicate keys.

IdentityHashMap was added in Java 1.4. It implements Map interface. But it doesn’t use equals() and hashCode() methods for comparing objects unlike other implementations of Map (e.g., HashMap).

Which is faster HashMap or IdentityHashMap?
Since IdentityHashMap uses == operator for comparing objects, it is faster compared to HashMap.

When to use IdentityHashMap?
It is suitable where we need reference equality check instead of logical equality.

NOTE:
Any implementation of Map interface is supposed to use equals() to compare objects, but IdentityHashMap doesn’t do that. So, it violates Map’s general contract. Hence it is easy to see that it is a special kind of Map which is rarely used.

IdentityHashMapDemo
import java.util.*;

class IdentityHashMapDemo
{
    IdentityHashMap hm = new IdentityHashMap();
    Integer i1 = new Integer(10);
    Integer i2 = new Integer(10);
    hm.put(i1, "Sachin");
    hm.put(i2, "Dravid");
    System.out.println(hm);
}
OUTPUT

{10=Sachin, 10=Dravid}

DESCRIPTION

THINGS TO TRY
  • What happens if we replace IdentityHashMap with HashMap in the above program?
    In that case, i1 and i2 are duplicate keys because i1.equals( i2 ) returns true. As a result, the output would be:
    {10=Dravid}
In the above program, keys i1 and i2 are not duplicate because i1 == i2 is false.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.