Sub topic 5
The hashCode Contract
Assume you can write Java classes with fields and constructors, use Set and Map, and override methods. This chapter focuses on the rule that connects hashCode() to equals().
What `hashCode()` returns
hashCode() is a method from java.lang.Object. It returns an int, a 32-bit signed integer that represents a hash value for the object.
A hash value is not a unique object identifier. Different objects can have the same hash value. This situation is called a collision.
The important contract is:
- If two objects are equal according to
equals(), they must return the same hash code. - If two objects are not equal, they may return the same hash code.
- During one execution of a program, repeated calls should return the same value unless information used by
equals()changes.
The second rule matters because an int has a limited number of values, while a program can create far more objects.
| Relationship | Required hash-code result |
|---|---|
| `a.equals(b)` is `true` | `a.hashCode() == b.hashCode()` must be `true` |
| `a.equals(b)` is `false` | Hash codes may be equal or different |
| The same object is unchanged | Repeated hash codes should remain the same |
Why equal objects need equal hash codes
Hash-based collections use the hash code to choose a storage area, often called a bucket. They then use equals() to compare objects within that bucket.
If equal objects produce different hash codes, they go to different buckets. The collection may not find an object that is logically present.
Implementing hashCode
Every field used by equals() must contribute to hashCode(). The exact formula is flexible. It only needs to satisfy the contract.
import java.util.Objects;
public final class UserId {
private final String value;
public UserId(String value) {
this.value = Objects.requireNonNull(value);
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof UserId)) return false;
UserId that = (UserId) other;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}Two UserId objects with the same text are equal, so their hashCode() results are also equal. The class is immutable, so its hash code cannot change after construction.
You can use Objects.hash when several fields participate:
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, birthYear);
}Do not include a field in hashCode() if equals() ignores that field. Doing so can give equal objects different hash codes.
The mutation hazard
If a mutable field affects equality and changes after an object is inserted into a HashSet or used as a HashMap key, the collection may search in the wrong bucket. Prefer immutable keys, or avoid changing equality-relevant state while the object is stored.
Exercise
A class compares only its id field in equals(). Should hashCode() use both id and name?
Show answer
No. It should use id only, because equal objects must produce the same hash code.