liveBook · Manning

IdentityHashMap

As explained in 100 Java Mistakes and How to Avoid Them

IdentityHashMap is a Java map implementation that compares keys by reference identity rather than by equals and hashCode.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Defines reference-identity comparison and gives a mutable-key workaround, but does not explain IdentityHashMap internals.
Examples
Uses a mutable List in HashSet and a StringBuilder collision scenario to expose lookup failures.
What you can do after
Apply it by choosing IdentityHashMap for mutable keys, or create identity-based sets with Collections.newSetFromMap.
How it connects
Connects mutable objects, equals(), hashCode(), compareTo(), HashMap, HashSet, and identity-based sets.

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.