IdentityHashMap class

IdentityHashMap

  • It is exactly same as HashMap except the following differences
  • In the case of HashMap JVM will always use “.equals()” method to identify duplicate keys, which is meant for content comparison.
  • But in the case of IdentityHashMap JVM will use == (double equal operator) to identify duplicate keys, which is meant for reference comparison.
package com.ashok.collections;

import java.util.Map;
import java.util.HashMap;
import java.util.IdentityHashMap;

public class MyIdentityHashMap {
   public static void main(String[] args) {
      Map hashmapObject = new HashMap();
      Map identityObject = new IdentityHashMap();

      hashmapObject.put(new String("key"), "Ashok");
      hashmapObject.put(new String("key"), "Vinod");

      identityObject.put(new String("identityKey"), "Ashok");
      identityObject.put(new String("identityKey"), "Vinod");

      System.out.println("HashMap after adding key :" + hashmapObject);
      System.out.println("IdentityHashMap after adding key :" + identityObject);
   }
}

Output
HashMap after adding key :{key=Vinod}
IdentityHashMap after adding key :{identityKey=Ashok, identityKey=Vinod}
IdentityHashMap class
Scroll to top