liveBook · Manning

Hash value

As explained in 100 Java Mistakes and How to Avoid Them

A hash code is an integer value returned by an object's hashCode method for use by hash-based data structures.

A hash value is an integer returned by hashCode() and used by hash-based collections. Two practical mistakes make it unreliable: misparenthesized expressions can damage distribution, while mutating a stored key can make it unreachable. section 2.1.1 section 8.6

Avoid these failure modes:

  • Parenthesize expressions that combine addition with bitwise shifts. Addition has higher precedence, so lo << 16 + hi means lo << (16 + hi), not (lo << 16) + hi. section 2.1.1
  • Do not modify an object after storing it as a HashMap key or HashSet element when the modification changes its hash value. Lookup uses the new bucket while the object remains in the old one. section 8.6
  • Treat static-analysis advice about parentheses as a prompt to verify intended semantics, not as proof that the existing expression is wrong. section 2.1.1

A damaged hash distribution

In a manual hashCode() implementation such as xmin + ymin << 8 + xmax << 16 + ymax << 24, shifts occur after the additions. The final left shift can erase 24 low-order bits, producing poor distribution and possible HashMap performance problems. Explicit parentheses isolate the intended operations. section 2.1.1

A key that disappears

Adding a List to a HashSet and then changing the list changes its hash value. set.contains(list) searches the bucket for the updated value instead of the bucket selected during insertion. section 8.6

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains operator grouping, bucket selection, and mutation effects, but stops short of defining a complete hashCode contract.
Examples
Uses packed-coordinate hashing, buffer-capacity arithmetic, mutable lists, BitSet keys, legacy dates, and StringBuilder.
What it assumes
Assumes familiarity with Java expressions and hash-based collections, while illustrating the relevant precedence and bucket behavior through focused examples.
What you can do after
Diagnose hash-based collection failures, inspect precedence, preserve intended grouping, and avoid mutating stored keys.
How it connects
Connects hash values with hashCode(), operator precedence, bitwise shift, HashMap, HashSet, mutability, equals(), and compareTo().

Also explained in

Compare how 7 books explain hash value →

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.