IdentityHashMap is a HashTable -based implementation of the Map Interface. Normal HashMap compares keys using the .equals method but Identity HashMap compares its keys using the == operator. Hence, ‘Java’ and new String(‘Java’) are considered as two different keys. The initial size of Identity HashMap is 21, while the initial size of a normal HashMap is 16.
Code Snippet:-
import java.util.IdentityHashMap; public class MyClass { public static void main(final String[] args) { final IdentityHashMap identityHashMap = new IdentityHashMap(); identityHashMap.put("Java", "Java-7"); identityHashMap.put(new String("Java"), "Java-8"); 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()); } }
Output:-
Key : Java and Value : Java-7 Key : Java and Value : Java-8 Size of map is : 2