Object.hashCode()
Returns the object's hash code — a number HashMap and HashSet use to find it quickly.
Available since: Java 1.0
Syntax
public int hashCode()Return value
intAn integer. Objects equal by equals() must have the same one.
Examples
Equal strings and records have equal hash codes:
record Point(int x, int y) {}
void main() {
IO.println("abc".hashCode());
IO.println("abc".hashCode() == new String("abc").hashCode());
IO.println(new Point(1, 2).hashCode() == new Point(1, 2).hashCode());
}Output:
96354
true
trueWhat happens if only equals() is overridden:
class Tag {
final String name;
Tag(String name) { this.name = name; }
@Override
public boolean equals(Object o) {
return o instanceof Tag t && t.name.equals(name);
}
}
void main() {
Set<Tag> tags = new HashSet<>();
tags.add(new Tag("java"));
IO.println(tags.contains(new Tag("java")));
}Output:
falseNotes
The contract: if a.equals(b), then a.hashCode() == b.hashCode(). The reverse is not required — different objects can share a hash. Above, contains() returned false because the two equal objects have different hash codes and HashSet looks in the wrong bucket. The easiest way to compute it is Objects.hash(fields...).
See also
- Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.
- Objects.hash() — Computes a hash code from several values — for implementing hashCode().
- record — Declares a record — an immutable data class with ready-made equals(), hashCode() and toString().
Related recipes
In the tutorial
- Equality and hash codes — Comparing objects in Java — == and equals, the equals and hashCode contract, Objects.equals and Objects.hash, records and the HashSet mistake.