Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

IdentityHashMap — an object-identity map

IdentityHashMap compares keys using == rather than equals, so distinct objects with equal contents can be separate keys. Learn put, get, containsKey, and size, including how to distinguish a missing entry from a null value.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

// Given K key and V value:
IdentityHashMap<K, V> map = new IdentityHashMap<>();
V previous = map.put(key, value);
V retrieved = map.get(key);
boolean present = map.containsKey(key);
int count = map.size();

java.util.IdentityHashMap<K, V> compares keys and values by reference identity (==), not equals. Unlike HashMap, it distinguishes separate objects that are equal according to equals. One use is tracking objects while deep-copying a graph.

IdentityHashMap.put(key, value) inserts an entry or replaces the value for the same key reference; it returns the previous value or null. IdentityHashMap.get(key) returns the value or null. IdentityHashMap.containsKey(key) checks for that exact reference, distinguishing an absent entry from a null value. IdentityHashMap.size() returns the entry count.

The map permits a null key and null values. It guarantees no ordering and is not synchronized. It deliberately violates the general Map contract based on equals; it is not a general-purpose map replacement.

In the example, two calls to new String("key") create different keys despite equal contents. Another put for a does not increase the size. The entry for b exists even though get(b) returns null.

Examples

import java.util.IdentityHashMap;

public class Main {
    public static void main(String[] args) {
        String a = new String("key");
        String b = new String("key");
        IdentityHashMap<String, String> map = new IdentityHashMap<>();

        map.put(a, "first");
        map.put(b, null);
        System.out.println(a.equals(b));
        System.out.println(a == b);
        System.out.println(map.size());
        System.out.println(map.put(a, "updated"));
        System.out.println(map.get(a));
        System.out.println(map.get(b));
        System.out.println(map.containsKey(b));
        System.out.println(map.containsKey(new String("key")));
    }
}

Result

true
false
2
first
updated
null
true
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources