IdentityHashMap compares keys by reference identity, regardless of their equals() and hashCode() implementations. This can preserve lookups when mutable key contents change, unlike ordinary hash-based collections. section 8.6
Use this approach cautiously:
- Prefer immutable keys for HashMap and HashSet; choose IdentityHashMap when mutable objects must remain keys. section 8.6
- Create an identity-based set with Collections.newSetFromMap(new IdentityHashMap<>()). section 8.6
- Do not confuse reference identity with content equality: identity semantics distinguish objects even when equals() considers them equivalent. section 8.6
Set<List<String>> set = new HashSet<>();
List<String> list = new ArrayList<>();
set.add(list);
list.add("Value");
System.out.println(set.contains(list)); #1
A mutable List added to HashSet becomes unfindable after its contents change, motivating identity-based key comparison. section 8.6
