What is the difference between HashMap and IdentityHashMap in terms of how they handle keys?

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.

Key Points: • HashMap treats two objects as the same key if equals() returns true and their hash codes match. • IdentityHashMap treats two keys as equal only when they reference the exact same object instance. • IdentityHashMap is mainly used in specialized scenarios such as object graph processing, caching, and maintaining object identity during serialization or framework internals.

Example: 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.

Code Example:

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());
    }
}

Interview Tip: 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.