IdentityHashMap in Java
So lets see the difference between HashMap and IdentityHashMap in Java,
- HashMap overrides equals() and hashcode() methods to compare objects, where as IdentityHashMap used only "==" operator to compare key and value. IdentityHashMap wont use object.hashCode() but uses System.identityHashCode(object) because we can use IdentityHashMap for mutable objects for whose hash code changes during the "in map" time frame.
- For example when we use HashMap the object values can be directly changed which leads to strange behavior while IdentityHashMap works fine.
- Next for using large maps which uses equals() and hashcode() will lead to expensive and in those cases we can switch to IdentityHashMap because both methods are not overridden in this class. Important using IdentityHashMap also specific to application.
These are major difference between HashMap and IdentityHashMap in Java. Now lets see simple example with both HashMap and IdentityHashMap implementation classes.
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
public class IdentityHashMapTest {
public static void main(String[] args) {
Map<String, String> hm = new HashMap<String, String>();
Map<String, String> ihm = new IdentityHashMap<String, String>();
hm.put("java", "111");
hm.put(new String("java"), "222");
hm.put("java", "333");
ihm.put("java", "111");
ihm.put(new String("java"), "222");
ihm.put("java", "333");
System.out.println("HashMap Size : "+hm.size());
System.out.println("IdentityHashMap Size : "+ihm.size());
System.out.println("HashMap Values : "+hm);
System.out.println("IdentityHashMap Values : "+ihm);
}
}
OUTPUT:
HashMap Size : 1
IdentityHashMap Size : 2
HashMap Values : {java=333}
IdentityHashMap Values : {java=333, java=222}
In above example if we see the size of both HashMap and IdentityHashMap is 1 and 2. Since HashMap overrides equals() and hashcode() methods it will compare object level of key and replaces for 1st 2 key and value which are trying to put in HashMap and remains only 1 key in Map.
Next when we see IdentityHashMap the size is 2, because "java" and new String("java") are considered as 2 different Objects. So it holds 2nd and 3rd value in Map.