CKTIS / Java
Overriding Object.hashCode() and the equals() contract
Objects that are equal according to `equals()` must have the same hash code. The reverse does not hold: matching hash codes do not prove equality.
Version: Java SE 21
Syntax
@Override
public int hashCode() {
return 31 * x + y;
}An Object.hashCode override replaces the inherited implementation with your class's no-argument public int hashCode() method. @Override lets the compiler check that the declaration really overrides a method. When you define value equality with equals(Object), also override hashCode() to match that definition. In the example, both methods use the coordinates x and y.
If a.equals(b) returns true, then a.hashCode() == b.hashCode() must also be true. The reverse does not hold: unequal objects can have the same hash code. That is a collision, not a contract violation.
Within one run, repeated hashCode() calls on the same object must give the same result as long as the data used by equals() does not change. The contract does not guarantee the same result across runs. A hash code is not a unique identifier.
HashMap uses the hash code to narrow the search and equals() to decide whether distinct key objects are equal. Many collisions can slow down lookups. Do not change data that affects equals() while an object is a map key: the map's behavior after such a change is unspecified.
Examples
import java.util.HashMap;
import java.util.Map;
public class Main {
private static final class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
return obj instanceof Point other && x == other.x && y == other.y;
}
@Override
public int hashCode() {
return 31 * x + y;
}
}
public static void main(String[] args) {
Point a = new Point(1, 0);
Point b = new Point(1, 0);
Point c = new Point(0, 31);
System.out.println(a.equals(b));
System.out.println(a.hashCode() == b.hashCode());
System.out.println(a.equals(c));
System.out.println(a.hashCode() == c.hashCode());
Map<Point, String> labels = new HashMap<>();
labels.put(a, "first");
labels.put(c, "second");
System.out.println(labels.get(b));
System.out.println(labels.get(c));
}
}Result
true true false true first second
`a` and `b` are separate objects with coordinates `(1, 0)`, so they are equal according to `equals()`. `c` has coordinates `(0, 31)` and is not equal to `a`, even though both hash codes are `31`. Looking up `b` returns `first`, the value stored under `a`, while looking up `c` returns `second`.
Related lessons
- Java · Lesson 28 · Intermediate · Version: 2