hashCode and equals in practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
The relationship between hashCode and equals is essential to hash map correctness. Violating this contract breaks lookups and causes subtle bugs.
The hashCode and equals contract
Equal objects must return the same hash code. The Point class below follows the rule by building hashCode() from the same fields that equals() compares.
static class Point { final int x, y; Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) { return o instanceof Point p && x == p.x && y == p.y; }
@Override public int hashCode() { return Objects.hash(x, y); // the same fields that equals() compares }}The equals()/hashCode() contract is a strict rule from the Java specification. Rule 1: If a.equals(b) is true, then a.hashCode() must equal b.hashCode(). Rule 2: If a.hashCode() == b.hashCode(), a.equals(b) is not necessarily true.
If you override equals(), you must also override hashCode() to maintain this contract. Suppose a Point class overrides equals but forgets hashCode. Point p1 = new Point(1, 2) gets identity hash 100 and sits in bucket 0.
Later, Point p2 = new Point(1, 2) gets identity hash 205 and checks bucket 5. Bucket 5 is empty, so map.get(p2) returns null. The entry is lost even though p1.equals(p2) is true.
- Equal objects rule: equal objects must always produce identical hash codes.
- Unequal objects rule: unequal objects may share the same hash code (a collision).
- Consistency:
hashCode()must return the same value as long as equality fields do not change.
- Identify all fields that determine object equality in
equals(). - Include every one of those fields when computing
hashCode(). - Use
Objects.hash(...)or prime multiplier formulas to combine fields. - Ensure map keys are immutable so their hash codes never change.
Find the bug
Find the hashCode bug
Tap the line that breaks the rule or the lookup.
Two equal points must find the same bucket.
Round 1 of 3Bad hash functions and slow maps
A hash function that returns the same number for every key is legal but slow. The program below compares a constant hash with one that uses both coordinates.
public class HashSpread { public static void main(String[] args) { int[][] points = {{1, 2}, {2, 1}, {3, 3}, {4, 0}}; for (int[] p : points) { int bad = 42; // constant: the same for every point int good = 31 * p[0] + p[1]; // uses both fields and the odd prime 31 System.out.println("(" + p[0] + ", " + p[1] + ") bad bucket " + bad % 16 + ", good bucket " + good % 16); } }}(1, 2) bad bucket 10, good bucket 1 (2, 1) bad bucket 10, good bucket 15 (3, 3) bad bucket 10, good bucket 0 (4, 0) bad bucket 10, good bucket 12
A bad hash function, such as one that returns a constant like 42, still satisfies the contract. However, it collapses every key into the exact same bucket. Lookup performance instantly degrades from average O(1) to linear O(n). A good hash function combines all equality fields using odd primes to spread values.
- Constant hash disaster: returning a fixed integer forces all entries into one bucket.
- Ignoring fields: omitting key fields from hashCode causes excessive collisions.
- Prime multiplication: multiplying by primes like 31 scatters bit patterns evenly.
Records as keys and mutable key dangers
A Java record writes equals() and hashCode() for you from its fields, so it is a safe map key. The examples show a record key, then a mutable key that goes missing.
Example 1 · Using a Java Record as a Safe HashMap Key
import java.util.HashMap;import java.util.Map;
public class RecordKeyDemo { record Point(int x, int y) {}
public static void main(String[] args) { Map<Point, String> map = new HashMap<>(); map.put(new Point(3, 4), "Target Location");
// Lookup with a new instance that is logically equal Point searchKey = new Point(3, 4); System.out.println("Found: " + map.get(searchKey)); }}Found: Target Location
What this code does
- Record generates equals() and hashCode() automatically.
- Distinct instances with identical coordinates produce the same hash code.
- The map locates and returns the target value reliably.
Example 2 · The Disaster of Mutating a Map Key
import java.util.HashMap;import java.util.Map;import java.util.Objects;
public class MutableKeyDemo { static class MutablePoint { int x, y; MutablePoint(int x, int y) { this.x = x; this.y = y; } public boolean equals(Object o) { if (!(o instanceof MutablePoint p)) return false; return x == p.x && y == p.y; } public int hashCode() { return Objects.hash(x, y); } }
public static void main(String[] args) { Map<MutablePoint, String> map = new HashMap<>(); MutablePoint pt = new MutablePoint(1, 2); map.put(pt, "Treasure");
// Mutating key field changes its hash code pt.x = 99; System.out.println("Lookup after mutation: " + map.get(pt)); }}Lookup after mutation: null
What this code does
- Mutating field x changes the object's hash code.
- map.get searches the bucket matching the new hash code.
- The entry remains trapped in the old bucket and cannot be found.
Example 3 · Memory Leak from Mutating Map Keys
import java.util.HashMap;import java.util.Map;import java.util.Objects;
public class MutableKeyLeakDemo { static class MutableKey { int id; MutableKey(int id) { this.id = id; } public boolean equals(Object o) { return (o instanceof MutableKey m) && id == m.id; } public int hashCode() { return Objects.hash(id); } }
public static void main(String[] args) { Map<MutableKey, String> map = new HashMap<>(); MutableKey key = new MutableKey(42); map.put(key, "data");
// Mutate key field after storage key.id = 99;
System.out.println("Found: " + map.containsKey(key)); System.out.println("Size: " + map.size()); }}Found: false Size: 1
What this code does
- Mutating key.id changes the hash code from hash(42) to hash(99).
- containsKey checks bucket for hash(99) and fails to find the entry.
- The entry remains trapped in the map, causing a silent memory leak.
Java records automatically generate correct equals() and hashCode() methods based on their components.
Record components are final and immutable by default, making records ideal map keys.
If a mutable key changes after insertion into a map, its hash code changes. The map will search the wrong bucket and fail to find the modified key.
- Record advantage: concise syntax with compiler-generated immutable equals and hashCode.
- Mutable key hazard: mutating a key after insertion makes it permanently lost in the map.
- Best practice: always use immutable objects like String, Integer, or records as map keys.
Finish up
Mark complete & continue
Next: Hashing in the real world