Sub topic 14
Overriding equals, hashCode, and toString
Every Java class inherits from Object, even when you never write extends. Object gives every class three methods that you will often override: equals, hashCode, and toString. The default versions rarely fit your own classes, so this chapter shows how to replace them correctly.
What the three methods do
| Method | Question it answers | Default behavior in `Object` |
|---|---|---|
| `equals(Object o)` | Do these two objects mean the same thing? | True only if both are the very same object |
| `hashCode()` | Which "bucket" should this object go in? | A number tied to the object's identity |
| `toString()` | How should this object look as text? | Class name plus a hex code, like `Point@1b6d3586` |
A hash code is a whole number that collections like HashSet and HashMap use to find objects quickly. Think of it as a shelf number in a library.
A worked example
Here is a Point class that overrides all three methods. Save it as Main.java.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
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 o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point other = (Point) o;
return x == other.x && y == other.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Point(" + x + ", " + y + ")";
}
}
public class Main {
public static void main(String[] args) {
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.println(a.equals(b)); // true
System.out.println(a); // Point(1, 2)
Set<Point> set = new HashSet<>();
set.add(a);
System.out.println(set.contains(b)); // true
}
}The equals method follows three steps:
- If both references point to the same object, return
true. - If the other object is not a
Point, returnfalse. Theinstanceofcheck also handlesnull. - Cast to
Pointand compare the fields.
Objects.hash(x, y) builds a hash code from the same fields that equals compares.
The parameter must be Object
Overriding only works when the parameter type matches exactly. Object.equals takes an Object. If you write equals(Point o) instead, you create a new overload, which is a separate method with the same name. Collections still call the old equals(Object), so your comparison is silently ignored.
Keep equals and hashCode together
Java has a rule: if two objects are equal, they must have the same hash code. A HashSet first looks for the object's bucket using hashCode, and only then calls equals inside that bucket.
If you override equals but not hashCode, two equal points will usually get different hash codes. The set then checks the wrong bucket and contains returns false.
toString makes debugging easier
println, string joining with +, and debuggers all call toString. A clear toString turns Point@1b6d3586 into Point(1, 2). This is polymorphism at work: println takes an Object, yet your version of toString runs.
Exercise
A class overrides equals to compare its fields but does not override hashCode. You add one object to a HashSet, then call contains with a different but equal object. What will usually happen, and why?
Show answer
contains will usually return false. The two objects use Object's default hashCode, which gives different numbers, so the set looks in a different bucket and never calls equals on the stored object.
Exercise
Why does writing public boolean equals(Point o) fail to override Object.equals?
Show answer
The parameter type is Point, not Object, so the signature differs. It becomes an overload. Code that calls equals(Object), such as HashSet, still runs Object's version. Adding @Override makes the compiler catch this.