Reference identity means that two references denote the same object instance, regardless of the objects’ contents. It matters when mutable objects are used as map keys or set elements: content-based equality and hash codes can change after insertion, breaking lookups. section 8.6
Use identity-based collections when object identity, rather than content, must remain stable:
- Use IdentityHashMap, which compares stored objects by reference identity regardless of equals() and hashCode(). section 8.6
- Create an identity-based set with Collections.newSetFromMap(new IdentityHashMap<>()). section 8.6
- Prefer immutable alternatives over legacy mutable keys such as java.util.Date; otherwise avoid mutation during the collection’s lifetime. 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 minimal HashSet example demonstrates how mutating a stored list can make ordinary content-based lookup unreliable. section 8.6







