Skip to main content
equals, hashCode, compareTo · Topic 3 of 6

The hashCode contract

Definition​

hashCode turns an object into a number that hash collections use to find it quickly. The rule: if two objects are equal, they must return the same hash code. Different objects may share a hash code, but a good spread keeps collections fast.

Example code​

Equal objects, same hash code

import java.util.Objects;

class Point {
private final int x, y;

Point(int x, int y) { this.x = x; this.y = y; }

@Override public boolean equals(Object o) {
return o instanceof Point p && x == p.x && y == p.y;
}

@Override public int hashCode() { return Objects.hash(x, y); } // built from the same fields as equals
}

class Demo {
public static void main(String[] args) {
Point a = new Point(3, 4);
Point b = new Point(3, 4);
Point c = new Point(4, 3);

System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode())); // equal => same hash
System.out.println(a.equals(c) + " " + (a.hashCode() == c.hashCode()));
}
}

// Output:
// true true
// false false

Finished this page? Track your progress (saved only in your browser).