IdentityHashMap Keys By Reference

Store keys by reference instead of equals: two distinct String instances with the same characters occupy two entries in an IdentityHashMap.

JavaData Integrity

Code

snippet
import java.util.IdentityHashMap;
import java.util.Map;

public class RefKeys {

    public static void main(String[] args) {
        // 字面量会驻留池:用 new String 造两个内容相同但独立的实例
        String keyA = new String("node-7");
        String keyB = new String("node-7");
        System.out.println("equals: " + keyA.equals(keyB));
        System.out.println("same ref: " + (keyA == keyB));

        // IdentityHashMap 判键用 == 而不是 equals:两个键位都保留
        Map<String, String> byRef = new IdentityHashMap<>();
        byRef.put(keyA, "first");
        byRef.put(keyB, "second");
        System.out.println("identity size: " + byRef.size());

        // 再放完全相同的引用:才是覆盖语义
        byRef.put(keyA, "overwritten");
        System.out.println("identity size: " + byRef.size());
        System.out.println("lookup by keyA: " + byRef.get(keyA));
    }
}

How the snippet works

The working surface is the class RefKeys and the function main — everything else is wiring.

Using it

The demo output is labeled (equals:, same ref:, identity size:), so every printed line maps back to its originating operation.

Key statements

Map<String, String> byRef = new IdentityHashMap<>();
String keyA = new String("node-7");
String keyB = new String("node-7");

Interactive Tools for This Topic

FAQ

What does IdentityHashMap Keys By Reference print when run?
Execute the whole file; each printed line is prefixed with a label like `equals:`, `same ref:`, `identity size:`.