Sub topic 7
Writing `hashCode` That Matches `equals`
This chapter assumes you know how to write Java classes, override methods, and use HashSet and HashMap. The key rule is simple:
> If two objects are equal according to equals, they must return the same value from hashCode.
The reverse is not required. Two unequal objects may have the same hash code. That situation is called a hash collision.
What `hashCode` does
hashCode returns an int derived from an object’s state. Hash-based collections use this number to choose a bucket, which is a smaller area where possible matches are stored.
When a collection searches for a key, it generally:
- Computes the key’s hash code.
- Selects a bucket from that hash code.
- Uses
equalsto check objects in that bucket.
The methods have different jobs:
| Method | Main job |
|---|---|
| `equals` | Decides whether two objects have the same logical value |
| `hashCode` | Finds a likely bucket quickly |
| `toString` | Produces a readable text form |
The hashCode contract
The Object contract has three important parts:
- During one execution, repeated calls to
hashCodeshould return the same value if the fields used byequalshave not changed. - If
a.equals(b)istrue,a.hashCode()must equalb.hashCode(). - Unequal objects do not need different hash codes, although different values usually improve performance.
The second rule is mandatory. If it fails, a HashSet can put an object in one bucket and search for an equal object in another bucket.
Implementing matching methods
Use exactly the same logical fields in both methods. Objects.hash is convenient for ordinary object and primitive fields.
import java.util.Objects;
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof Point)) return false;
Point point = (Point) other;
return x == point.x && y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Point{x=" + x + ", y=" + y + "}";
}
public static void main(String[] args) {
Point first = new Point(2, 3);
Point second = new Point(2, 3);
System.out.println(first.equals(second)); // true
System.out.println(first.hashCode() == second.hashCode()); // true
}
}Do not add a field to equals without adding it to hashCode. Do not add a field to hashCode that equals ignores. Either mismatch makes the implementation inconsistent.
Common failure
Overriding equals alone is a bug:
class Tag {
final String name;
Tag(String name) {
this.name = name;
}
@Override
public boolean equals(Object other) {
return other instanceof Tag
&& name.equals(((Tag) other).name);
}
// Missing hashCode
}Tag inherits Object.hashCode, which is usually based on object identity. Two equal Tag objects can therefore have different hash codes. Add @Override to both methods so the compiler helps detect mistakes.
Exercise
If a.equals(b) is true, may a.hashCode() and b.hashCode() differ?
Show answer
No. Equal objects must have equal hash codes. Unequal objects may share a hash code.