liveBook · Manning

Identity

As explained in 100 Java Mistakes and How to Avoid Them

Reference identity is the property of two references denoting the same object instance, regardless of object content.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains reference-based comparison, contrasts mutable-key hazards, and names identity-based collection implementations.
Examples
Uses a mutable list in a HashSet and recommends IdentityHashMap-based map and set alternatives.
What you can do after
Apply identity semantics through IdentityHashMap and its set adapter, while preventing mutation-related lookup failures.
How it connects
Connects reference identity with equals(), hashCode(), HashMap, HashSet, mutable objects, and IdentityHashMap.

Also explained in

Compare how 8 books explain identity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.