Sub topic 6
Why HashMap and HashSet need both methods
This chapter assumes you know how equals and hashCode are defined and what the two contracts say. It also assumes you have used Set and Map from java.util. Here you will see how HashMap and HashSet use the two methods together, and why a class that overrides only one of them behaves wrongly.
What a hash table does
A HashMap stores its entries in an array of buckets. The default array has 16 slots and grows as it fills. A lookup does not scan every entry. It uses the key's hash code to jump to one bucket, then compares only the few entries in that bucket.
The two methods have different jobs:
hashCodepicks the bucket. It narrows the search from "all entries" to "a few candidates".equalsmakes the final decision. It confirms which candidate, if any, is the same key.
Neither method can do the other's job. hashCode alone cannot confirm a match, because two different keys may share a hash code. equals alone cannot find the bucket, because the map would have to call it on every entry.
The lookup, step by step
For map.get(key), the OpenJDK implementation does roughly this:
- Call
key.hashCode()and scramble the result withh ^ (h >>> 16). This mixes the high bits into the low bits, so keys whose hash codes differ only in the upper bits still spread out. - Compute the bucket index as
(tableLength - 1) & hash. The table length is always a power of two, so this keeps only the low bits. - Walk the entries in that bucket. For each entry, first compare the stored hash with the lookup hash.
- If the hashes match, check whether the stored key is the same reference as the lookup key. If it is not, call
key.equals(storedKey). - Return the value of the first entry that matches. If none match, return
null.
Step 3 matters for the bugs below. equals runs only for entries whose hash equals the lookup hash. If two objects that you consider equal have different hash codes, equals is never asked about them.
HashSet has no separate mechanism. It wraps a HashMap and stores each element as a key with a dummy value. So set.add(x) is a put, and set.contains(x) is a containsKey. Everything in this chapter applies to both.
Bug 1: equals without hashCode
The contract says equal objects must have equal hash codes. If you override equals and leave hashCode alone, you inherit Object.hashCode, which derives its value from the object's identity. Two separately created objects almost always get different values.
import java.util.HashSet;
import java.util.Set;
public class MissingHashCode {
static class Tag {
final String name;
Tag(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
return o instanceof Tag && ((Tag) o).name.equals(name);
}
// hashCode is NOT overridden: this is the bug
}
public static void main(String[] args) {
Set<Tag> tags = new HashSet<>();
tags.add(new Tag("java"));
System.out.println(tags.contains(new Tag("java"))); // almost always false
tags.add(new Tag("java"));
System.out.println(tags.size()); // almost always 2
}
}The two Tag("java") objects are equal according to equals. But the set hashes the lookup object, goes to a bucket that most likely does not hold the stored one, and finds nothing. The set can also fail to reject duplicates, so size() is usually 2.
The result is not an exception. The code compiles and runs, and the collection returns wrong answers. The bug is sometimes intermittent: if the two identity hashes happen to land in the same bucket and have the same hash value, the lookup succeeds. That is very rare, but it means a test can pass once and fail on the next run.
The fix is to override hashCode from the same fields that equals uses:
@Override
public int hashCode() {
return name.hashCode();
}Bug 2: hashCode without equals
The opposite mistake is less common but just as real. If you override hashCode and keep the inherited equals, the hash code leads the lookup to the right bucket. Then equals falls back to reference comparison and rejects the match, unless you pass in the very same object that is stored.
The result is the same: contains returns false for an object that is logically present, and duplicates get through. The collection needs the two methods to agree. A hash code without a matching equals only gets you to the right bucket.
Collisions are allowed
The contract is one-directional:
- Equal objects must have equal hash codes.
- Unequal objects may have equal hash codes.
When two unequal keys land in the same bucket, that is a collision. A HashMap handles collisions correctly because equals decides the match. A bad hash function only makes lookups slower. A missing or inconsistent one makes them wrong.
The following program counts how often equals is called during one lookup. It compares well-spread hash codes with a hash code that is the same for every key.
import java.util.HashMap;
import java.util.Map;
public class CountingKey {
static int equalsCalls = 0;
static class Key {
final int id;
final int hash;
Key(int id, int hash) {
this.id = id;
this.hash = hash;
}
@Override
public boolean equals(Object o) {
equalsCalls++;
return o instanceof Key && ((Key) o).id == id;
}
@Override
public int hashCode() {
return hash;
}
}
public static void main(String[] args) {
Map<Key, String> spread = new HashMap<>();
for (int i = 0; i < 100; i++) {
spread.put(new Key(i, i), "v" + i);
}
equalsCalls = 0;
spread.get(new Key(42, 42));
System.out.println("distinct hashes: " + equalsCalls); // 1
Map<Key, String> clashing = new HashMap<>();
for (int i = 0; i < 5; i++) {
clashing.put(new Key(i, 7), "v" + i);
}
equalsCalls = 0;
clashing.get(new Key(4, 7));
System.out.println("same hash: " + equalsCalls); // 5
}
}With distinct hash codes, one equals call confirms the match. When all keys share one hash code, they sit in one bucket and the lookup compares against each entry in turn. With 5 keys that is 5 calls. With 100,000 keys it would be 100,000 calls, which is why a constant hashCode is legal but ruinous.
Since Java 8, a bucket with many entries (8 or more, in a table of at least 64 slots) is converted to a balanced tree. This limits the damage to roughly logarithmic time when keys are Comparable. You should not rely on it as a substitute for a good hash function.
Summary of failure modes
| Situation | What the map does | Visible symptom |
|---|---|---|
| Both methods consistent | Finds bucket, confirms with `equals` | Correct behavior |
| `equals` overridden, `hashCode` not | Equal objects go to different buckets | `contains` and `get` miss; duplicates accepted |
| `hashCode` overridden, `equals` not | Right bucket, but `equals` compares references | `contains` and `get` miss for equal copies |
| Same `hashCode` for every object | Everything shares one bucket | Correct but slow |
| Key fields change after insertion | Stored hash no longer matches current hash | Entry present but unreachable by key |
The last row is the subject of a later chapter on mutable keys. The cause is already visible here. The map stores the hash it computed at insertion time, and it never recomputes it. If a key's fields change, a lookup with that key hashes to a different bucket than the one where it was stored.
Practical rules
- Override
equalsandhashCodetogether, and base both on the same fields. - Compute
hashCodeonly from fields thatequalsalso compares. A field used inhashCodebut ignored byequalsbreaks the contract. - A field that
equalscompares buthashCodeignores is legal, but it causes more collisions. - Use immutable keys wherever you can. A
Stringor anIntegeris a safe key because its hash cannot change.
Exercise
A class Account overrides equals to compare an id field but does not override hashCode. A developer runs Set<Account> set = new HashSet<>(); set.add(new Account(5)); System.out.println(set.contains(new Account(5))); and sees true once, then false on later runs. Explain how this can happen and what the fix is.
Show answer
Without a hashCode override, each object gets an identity-based hash code, so the two Account(5) objects normally have different hashes. HashSet calls equals only on entries in the bucket selected by the lookup hash, and only when the stored hash equals the lookup hash. Usually the lookup goes to a different bucket, or the hashes differ, so the result is false. In rare runs the two identity hashes happen to be equal, so equals is called and returns true. The fix is to add @Override public int hashCode() { return Integer.hashCode(id); } (or Objects.hash(id)), so that equal accounts always produce the same hash.
Exercise
In the CountingKey program, what would equalsCalls be after clashing.get(new Key(4, 7)) if the map held 5 keys that all had hash code 7, and why does the lookup not need to call equals on keys in other buckets?
Show answer
It would be 5, because all 5 entries share one bucket and the key with id 4 is the last one checked. A lookup computes the bucket from the hash code and examines only that bucket. Entries in other buckets are never visited, so equals is never called on them.