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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.MIME Type LookupResolve a file extension, file name, or MIME type to its media type, category, and related extensions using a local reference table.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.