8 Difference between IdentityHashMap and HashMap with Example

HashMap is one of the most frequently used class in java collections framework. In this post we will learn about the difference between IdentityHashMap and HashMap with example. We will also look at the similarities between these two classes. I have already discussed the interview questions on collections .

Read Also :  How Remove method works Internally in HashMap with Example


Difference between IdentityHashMap and HashMap in Java

1. Equality used(Reference Equality instead of Object Equality) : IdentityHashMap uses reference equality to compare keys and values while HashMap uses object equality to compare keys and values .
for example :

Suppose we have two keys k1 and k2


In HashMap :
two keys are considered equal   if and only if (k1==null ? k2==null  : k1.equals(k2))

// object equality i.e using equals() method to compare objects


In IdentityHashMap :
two keys are considered equal  if and only if (k1 == k2)   

//reference equality  i.e  using == operator  to compare objects



2. Map's contract violation :  IdentityHashMap implements the Map interface,  it intentionally violates the Map general contract , which mandates the use of equals method when comparing objects.


HashMap also implements Map interface but it does not violate the Map general contract  as it uses equals method  to compare objects .

3. Hashcode method :   IdentityHashMap does not use hashCode() method instead it uses System.identityHashCode() to find bucket location.
HashMap uses hashCode() method to find bucket location. Find the detailed explanation  here
how hashmap works in java.

4. Immutable keys : IdentityHashMap does not require keys to be immutable as it does not relies on equals() and hashCode() method.
To safely store the object in HashMap keys must be immutable.

5. Performance : According to IdentityHashMap Oracle docs,
IdentityHashMap will yield better performance than HashMap(which uses chaining rather than linear probing Hashtable)  for many jre implementations and operation mixes

6. Implementation : Both IdentityHashMap and HashMap are  Hashtable based implementation of Map interface. IdentityHashMap is a simple linear probe hashtable  while HashMap uses chaining instead of linear probe in hashtable.

7. Initial capacity of default constructor : Initial capacity of HashMap is 16 by default .  Initial capacity of IdentityHashMap is 21 by default.

8. Added to jdk : IdentityHashMap is added to jdk in java version  1.4 . HashMap class is introduced to the java development kit in java version 1.2 .



Example of IdentityHashMap and HashMap 



import java.util.Map;
import java.util.HashMap;
import java.util.IdentityHashMap;
public class IdentityHashMapExample { public static void main(String[] args) { 
 
           
       // Created HashMap and IdentityHashMap objects

        Map hashmapObject = new HashMap();
        Map identityObject = new IdentityHashMap();
        
       
       // Putting  keys and values in HashMap and IdentityHashMap Object

        hashmapObject.put(new String("key") ,"Google"); 
        hashmapObject.put(new String("key") ,"Facebook"); 
       
        identityObject.put(new String("identityKey") ,"Google"); 
        identityObject.put(new String("identityKey") ,"Facebook"); 


        // Print HashMap and IdentityHashMap Size : After adding  keys
       
        System.out.println("HashMap after adding key :"+ hashmapObject);
        System.out.println("IdentityHashMap after adding key :"+ identityObject); 
                            
 }
}




Output :


HashMap after adding key :{key=Facebook}
IdentityHashMap after adding key :{identityKey=Facebook, identityKey=Google}

 

Similarities between IdentityHashMap and HashMap

1. Permit null key and null values : Both HashMap and IdentityHashMap class permit null key and null values.

2. Not synchronized : Both classes are not synchronized. Both classes must be synchronized externally.
For IdentityHashMap :
Map m  = Collections.synchronizedMap(new IdentityHashMap( ... ));
For HashMap :
Map m  = Collections.synchronizedMap(new HashMap( ... ));

3. Iterators returned by the iterator method : Both classes iterator method return the fail-fast iterator . Check out in detail about the difference between fail-fast iterator and fail-safe iterator .

4. Implementation : Both are Hashtable based implementation of Map interface.

When to prefer IdentityHashMap over HashMap

According to Oracle docs , IdentityHashMap  class is not a general purpose Map implementation , while WeakHashMap class implements the Map interface , it intentionally violates Map's general contract , which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.


Difference between IdentityHashMap and HashMap in Java with example
A typical use of this class is topology-preserving object graph transformations , such as serialization and deep copying . To perform such a transformation , a program must maintain a "node table" that keeps track of all the object references that have already been processed.The node table must not equate distinct objects even if they happen to be equal.

Another typical use of this class is to maintain proxy objects. For example , a debugging facility might wish to maintain a  proxy object for each object in the program being debugged.



Recap: Difference between IdentityHashMap and HashMap in Java


IdentityHashMapHashMap
Equality usedReference(==)Object(equals method)
Maps contract violationYesNo
HashCode method usedSystem.identityHashCode()Object class hashCode() method
Immutable keysNo requirementYes
PerformanceFastSlow in comparision
Implementationlinear-probechaining
Initial capacity of Default constructor 1621
Added to jdkjdk 1.4jdk 1.2


Please mention in the comments in case you have any questions regarding the difference between IdentityHashMap and HashMap in java .

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry