HashMap and IdentityHashMap differ primarily in how they determine whether two keys are the same. HashMap compares keys based on logical equality using the equals() and hashCode() methods, whereas IdentityHashMap compares keys using reference equality (==), meaning it checks whether both references point to the exact same object in memory.
Two String objects containing the value "Java" are considered the same key in a HashMap because their contents are equal. However, IdentityHashMap treats them as different keys if they are separate object instances, even though they contain identical data.
import java.util.HashMap;
import java.util.IdentityHashMap;
public class MapExample {
public static void main(String[] args) {
String key1 = new String("Java");
String key2 = new String("Java");
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put(key1, "Value1");
hashMap.put(key2, "Value2");
System.out.println("HashMap Size: " + hashMap.size());
IdentityHashMap<String, String> identityMap =
new IdentityHashMap<>();
identityMap.put(key1, "Value1");
identityMap.put(key2, "Value2");
System.out.println("IdentityHashMap Size: " +
identityMap.size());
}
}A concise interview answer is: HashMap uses equals() and hashCode() to compare keys based on logical equality, while IdentityHashMap uses the == operator to compare object references. As a result, IdentityHashMap considers two keys equal only if they are the exact same object in memory.
Last updated: 1 November 2026
Previous question: What would happen if you override only the equals() method and not hashCode() in a custom key class used in HashMap?
Next question: How does Collections.sort() work internally?