Java Reference ยท Object-Oriented Concepts
The equals() and hashCode() contract in Java
Reference for the Java equals() and hashCode() contract: the five equals rules, why equal objects need equal hash codes, and what breaks in HashMap and HashSet.
Every class inherits equals(Object) and hashCode() from Object. The inherited versions compare identity: two references are equal only if they point at the same object. Value-like classes such as points, money amounts and identifiers usually want value equality instead, so they override both methods.
The two methods are bound by a contract. If two objects are equal according to equals, they must return the same hashCode(). Hash-based collections (HashMap, HashSet, ConcurrentHashMap) rely on this: they use the hash code to pick a bucket and equals to find the entry inside it. Break the contract and lookups silently fail.
@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); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
The contract
The rules for equals on non-null references:
| Rule | Meaning |
|---|---|
| Reflexive | x.equals(x) is true. |
| Symmetric | x.equals(y) is true exactly when y.equals(x) is. |
| Transitive | If x.equals(y) and y.equals(z), then x.equals(z). |
| Consistent | Repeated calls give the same answer while the compared state does not change. |
| Null-safe | x.equals(null) is false, never an exception. |
The rule for hashCode: equal objects must have equal hash codes, and the value must stay the same during one run as long as the fields used by equals do not change. The reverse is not required: unequal objects may share a hash code (a collision), though fewer collisions mean faster maps.
Syntax
public boolean equals(Object obj) public int hashCode()
| Name | Description |
|---|---|
obj |
The object to compare with. May be null. |
Returns (equals) |
true if the objects are considered equal. |
Returns (hashCode) |
An int hash. Any value is legal as long as it follows the contract. |
Helpers that make the methods short:
| Method | Use |
|---|---|
Objects.equals(a, b) |
Null-safe field comparison. |
Objects.hash(f1, f2, ...) |
Combines fields into a hash (allocates a varargs array). |
Objects.hashCode(o) |
0 for null, else o.hashCode(). |
Double.compare, Float.compare |
Compare floating-point fields; == treats NaN and -0.0 differently from equals. |
Arrays.equals, Arrays.hashCode |
Array fields compare contents instead of identity. |
Usage notes
- Override both or neither. Overriding only
equalsis the classic bug shown above:HashSet.containsandHashMap.getfail for logically equal keys. - Use the same fields in both methods. A field used in
hashCodebut not inequalsis harmless; the opposite violates the contract. - Do not hash mutable fields of keys. If a key's hash changes after it is put in a map, the entry is stranded in the wrong bucket and cannot be found. Prefer immutable key classes (see immutable classes).
- Parameter type is
Object. Writingequals(Point p)overloads rather than overrides;@Overridecatches the mistake at compile time. - Inheritance makes symmetry hard. A subclass that adds a field and compares it cannot stay symmetric with its parent when you use
instanceof. Either comparegetClass()for exact types, make the classfinal, or prefer composition. - Records generate
equals,hashCodeandtoStringfrom all components. Enums use identity, which is correct for them. - Performance:
hashCodeshould be cheap.Stringcaches its hash. For classes with many fields you can cache the value in a field if the class is immutable. - Arrays use identity
equals; useArrays.equalsorList.of(...)when you need content equality. - Comparison with
Comparable: sorted collections such asTreeSetusecompareTo, notequals; keep the two consistent or the set will look odd.
Related
toString(), Immutable classes,Object,record- Lessons: The Object class, How HashMap works, Records