liveBook · Manning

Hash collision

As explained in 100 Java Mistakes and How to Avoid Them

A hash collision occurs when distinct inputs to a hash function produce the same hash value or map to the same hash-table location.

A hash collision occurs when distinct objects produce the same hash value. HashMap and HashSet may treeify a heavily colliding bucket, using compareTo() alongside hashCode() and equals(). section 8.6

A crafted StringBuilder collision

A demonstration creates 40 StringBuilder objects in one bucket, finds another object with a matching hash code, inserts it, and then mutates it. After mutation, contains(sb) returns false because the set can no longer locate the changed key. section 8.6

Avoid collision-related collection failures by:

  • Keeping objects used as HashMap keys or HashSet elements immutable while stored. section 8.6
  • Treating identity-based hash codes as implementation-dependent; collision distributions are not guaranteed by the JVM specification. section 8.6

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Demonstrates crafted collisions, bucket treeification, and mutation failure while stopping short of general collision algorithms.
Examples
Uses StringBuilder objects, a deliberately colliding bucket, and post-insertion mutation to expose lookup failure.
What you can do after
Diagnose/debug collection lookups by checking key mutation, hash collisions, and inconsistent equals() and compareTo() behavior.
How it connects
Connects hash collisions with HashMap, HashSet, hashCode(), equals(), compareTo(), mutable objects, and red-black trees.

Also explained in

Compare how 4 books explain hash collision →

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.