newSetFromMap adapts any Map implementation into a Set backed by it, so an IdentityHashMap can back a Set that compares elements by reference instead of equals.
Set<String> identitySet = Collections.newSetFromMap(new IdentityHashMap<>());
String a = new String("dup");
String b = new String("dup");
identitySet.add(a);
identitySet.add(b);
System.out.println("Identity-backed set size: " + identitySet.size());
Set<String> normalSet = new HashSet<>();
normalSet.add(a);
normalSet.add(b);
System.out.println("Hash-backed set size: " + normalSet.size());
Identity-backed set size: 2
Hash-backed set size: 1
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27