Sub topic 5
The hashCode contract
This chapter assumes you can write a Java class with fields and a constructor, you know how equals compares objects, and you have used HashMap and HashSet. Here you learn the rules hashCode must follow, the code that breaks them, and how to tell a legal implementation from a good one.
What hashCode is for
hashCode() is declared in java.lang.Object and returns an int. Hash-based collections such as HashMap, HashSet, and Hashtable use that number to decide where to look for an object. The hash code is a quick pre-filter. It narrows the search to a small group of candidates, and then equals makes the final decision.
The default implementation in Object is derived from the object's identity, usually its memory address or an internal identity value. Two distinct objects therefore get different hash codes in practice, even if all their fields match. That default is consistent with the default equals, which also compares identity. Once you override equals, the default hashCode no longer matches it.
The rules
The Object.hashCode documentation states three requirements.
| Rule | Meaning | Who must follow it |
|---|---|---|
| Consistency | While the object is unchanged in the fields used by `equals`, repeated calls in one run return the same value. | Every class |
| Equal objects, equal codes | If `a.equals(b)` is true, then `a.hashCode() == b.hashCode()`. | Every class that overrides `equals` |
| Unequal objects, no requirement | If `a.equals(b)` is false, the codes may be the same or different. | Nobody, but distinct codes improve speed |
The second rule is the one programmers break. It runs in one direction only. Equal objects must have equal hash codes, but equal hash codes say nothing about equality.
The contrapositive in the diagram is what makes hash tables fast. If two hash codes differ, the collection knows the objects are not equal and skips the equals call.
Breaking rule 2
This program overrides equals but not hashCode.
import java.util.HashSet;
import java.util.Set;
public class BrokenTag {
static final 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) {
Tag a = new Tag("java");
Tag b = new Tag("java");
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // almost always false
Set<Tag> tags = new HashSet<>();
tags.add(a);
System.out.println(tags.contains(b)); // almost always false
}
}a and b are equal, yet contains reports false. The set computes b.hashCode(), which comes from identity and differs from a's code. It looks in a bucket where a is not stored, finds nothing, and never calls equals.
The failure is silent. There is no exception, and the result is "almost always" wrong rather than always wrong. Two identity hash codes can occasionally land in the same bucket, so a test can pass by luck.
Fixing it
The simplest correct implementation hashes exactly the fields that equals compares.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class FixedTag {
static final 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);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
public static void main(String[] args) {
Set<Tag> tags = new HashSet<>();
tags.add(new Tag("java"));
System.out.println(tags.contains(new Tag("java"))); // true
}
}Objects.hash(Object...) combines the values with the same formula as Arrays.hashCode: start at 1, then for each value compute 31 * result + valueHash. For the values 1 and 2 this gives 31 (31 1 + 1) + 2 = 994. The call also handles null values, which contribute 0.
Rule 3: collisions are legal
Different objects may share a hash code. This is called a collision, and it cannot be avoided in general, because there are only about 4.3 billion int values and far more possible objects. The String class shows it clearly.
public class Collision {
public static void main(String[] args) {
System.out.println("Aa".hashCode()); // 2112
System.out.println("BB".hashCode()); // 2112
System.out.println("Aa".equals("BB")); // false
}
}The two strings are unequal and have equal hash codes. Nothing is wrong. A hash-based collection puts both in the same bucket and uses equals to tell them apart.
Legal but slow
The contract does not require good distribution, so a constant is a valid hashCode.
@Override
public int hashCode() {
return 42; // correct per the contract, terrible for performance
}Every object lands in the same bucket. A lookup must then compare against every entry in that bucket. Since Java 8, HashMap converts crowded buckets into balanced trees. That helps when keys implement Comparable, but for other key types it can still degrade toward linear time. A set of 100,000 such keys behaves like a list.
A good hash code spreads unequal objects across many values. Combining every significant field, as Objects.hash does, is usually enough. The multiplier 31 is an odd prime that reduces patterns in the output, and 31 * i can be computed as (i << 5) - i.
Fields: hash the same ones as equals, or fewer
The relationship between the fields in equals and hashCode has a precise rule.
- Every field used in
hashCodemust also be used inequals. IfhashCodeincludes a field thatequalsignores, two equal objects can have different hash codes. That breaks rule 2. - A field used in
equalsmay be left out ofhashCode. The result is still correct, but more collisions occur.
Suppose a User class treats two users as equal when their id matches, but its hashCode also mixes in lastLogin. Two copies of the same user loaded at different times are equal yet land in different buckets. Keep the hashed fields a subset of the compared fields.
Consistency and mutable fields
Rule 1 says the value must not change while the compared fields stay the same. The corollary is that if a compared field changes, the hash code changes too. This is correct behavior, but it is dangerous when the object is already stored in a hash collection.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MutableKey {
public static void main(String[] args) {
List<Integer> key = new ArrayList<>(List.of(1));
Map<List<Integer>, String> map = new HashMap<>();
map.put(key, "value");
key.add(2); // changes key.hashCode() after it was stored
System.out.println(map.get(key)); // null
System.out.println(map.get(List.of(1))); // null
System.out.println(map.containsValue("value")); // true
}
}The entry is still in the map, but stored under the old hash code. The map looks for key using its new hash code and finds nothing. It looks for List.of(1) using the old hash code, finds the bucket, but equals fails against the mutated list. The safe habit is to use immutable objects as keys.
Stability across runs
Consistency applies only within one execution of a program. The contract does not promise the same value on another run. For Object's default, values differ between runs. Some classes document their formula, such as String, Integer, and List, and those values are stable. Even so, do not persist hash codes in files or databases, and do not use them as identifiers. Use them only to place objects in in-memory hash structures.
Checklist for an implementation
- Override
hashCodewhenever you overrideequals. - Use only fields that
equalsalso compares. - Use
Objects.hashfor ordinary fields,Arrays.hashCodefor arrays, and avoidObjects.hashon a single array argument, since it would hash the array's identity. - Prefer immutable fields so the value never changes after the object is stored in a collection.
- Do not depend on the exact numeric value outside the object's own class.
Exercise
A class Account defines equals to compare only id. Its hashCode returns Objects.hash(id, balance). Does this satisfy the hashCode contract? Explain what goes wrong, and give a corrected method.
Show answer
No. Two Account objects with the same id but different balance are equal, yet their hash codes differ. This breaks rule 2 (equal objects must have equal hash codes), so a HashSet<Account> can fail to find an account that is equal to one it holds. The fix is to hash only fields that equals compares: public int hashCode() { return Objects.hash(id); }. Hashing a subset of the compared fields is legal. Hashing a field that equals ignores is not.