Criteria IdentityHashMap HashMap
Key Comparison Uses reference equality (==) for comparing keys Uses equals() method for comparing keys
Use-case Used when reference-based comparison is required for keys General-purpose map used for object-based key comparison
Null Keys and Values Allows both null keys and values Allows one null key and multiple null values
Performance May offer faster lookups for large numbers of keys which are distinct objects (due to reference-based comparison) Faster for keys with properly overridden equals() and hashCode() methods
Implementation Does not use the hashCode() method of keys; uses System.identityHashCode(obj) for each key Uses the hashCode() method of keys for hashing
Thread Safety No No
Size Expected maximum size should be specified during initialization, or it will be twice the current size when resizing is needed Resizes when it crosses a threshold, typically when it’s about 75% full

Example: Difference Between IdentityHashMap and HashMap in Java

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

public class IdentityHashMapVsHashMapDemo {

    public static void main(String[] args) {
        // Using a HashMap
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put(new String("key"), "Value1");
        hashMap.put(new String("key"), "Value2");

        // Using an IdentityHashMap
        Map<String, String> identityHashMap = new IdentityHashMap<>();
        identityHashMap.put(new String("key"), "Value1");
        identityHashMap.put(new String("key"), "Value2");

        // Printing values
        System.out.println("hashMap size: " + hashMap.size());
        System.out.println("identityHashMap size: " + identityHashMap.size());
    }
}

Output:

hashMap size: 1
identityHashMap size: 2

Explanation:

1. HashMap: It uses the equals() method for comparing keys (and values). So when we use two different String objects with the same content as keys, it sees them as equivalent and overwrites the first with the second.

2. IdentityHashMap: It uses reference-equality (==) in place of object-equality (equals()) for comparing keys (and values). So even if two keys are logically equal (have equal content), they are treated as two different keys if they refer to different objects.

3. In the provided example:

– We create a HashMap and put two different String objects (but with the same content "key") into it. The second entry overwrites the first one because the keys are considered equal based on the equals() method. Therefore, the size of the hashMap becomes 1.

– We create an IdentityHashMap and put the same two different String objects into it. Both are considered different keys because they refer to different memory addresses. Therefore, the size of the identityHashMap becomes 2.

4. IdentityHashMap is not a general-purpose Map implementation and should be used only in special cases where reference-equality semantics are required.