Java IdentityHashMap Example

IdentityHashMap class is not a general-purpose Map implementation! While this 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.

IdentityHashMap is a HashTable based implementation of Map Interface. Normal HashMap compares keys using '.equals' method. But Identity HashMap compares its keys using '==' operator.

IdentityHashMap Class Example

As we know that IdentityHashMap is a HashTable based implementation of Map Interface. Normal HashMap compares keys using '.equals' method. But Identity HashMap compares its keys using '==' operator. Hence 'a' and new String('a') are considered as 2 different keys. The initial size of Identity HashMap is 21 while the initial size of normal HashMap is 16.
import java.util.IdentityHashMap;

public class IdentityHashMapExample {
 public static void main(final String[] args) {
   final IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<String, String>();

         identityHashMap.put("a", "Java");
         identityHashMap.put(new String("a"), "J2EE");
         identityHashMap.put("b", "J2SE");
         identityHashMap.put(new String("b"), "Spring");
         identityHashMap.put("c", "Hibernate");

         for (final String str : identityHashMap.keySet()) {
             System.out.println("Key : " + str + " and Value : " + identityHashMap.get(str));
         }

         System.out.println("Size of map is : " + identityHashMap.size());
         System.out.println("Here 'a' and new String('a') are considered as separate keys");
 }
}
Output:
Key : a and Value : Java
Key : b and Value : J2SE
Key : c and Value : Hibernate
Key : b and Value : Spring
Key : a and Value : J2EE
Size of map is : 5
Here 'a' and new String('a') are considered as separate keys
Note that in the above output keys - 'a' and new String('a') are considered as 2 different keys.

Reference

Comments