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.
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());
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?