What is IdentityHashMap in Java?

An IdentityHashMap in Java is a collection class that uses reference equality instead of object equality when comparing keys. This means that two keys are considered equal only if they refer to the same object in memory, rather than if they are logically equivalent. This behavior is useful in specific scenarios where you want to maintain the identity of the objects rather than their content.

IdentityHashMap is part of the Java Collections Framework and is similar to HashMap, but with the difference in the equality check. It is particularly efficient when the keys are instances of the same class and are frequently compared for reference equality.

Example of IdentityHashMap in Java

import java.util.IdentityHashMap; public class IdentityHashMapExample { public static void main(String[] args) { IdentityHashMap idMap = new IdentityHashMap<>(); String key1 = new String("Key"); String key2 = new String("Key"); idMap.put(key1, 1); idMap.put(key2, 2); // This will print 1 because key1 and key2 are different references System.out.println("Value for key1: " + idMap.get(key1)); System.out.println("Value for key2: " + idMap.get(key2)); System.out.println("Size of IdentityHashMap: " + idMap.size()); } }

IdentityHashMap Java Collections Reference Equality Key Comparison Java HashMaps