Sub topic 4
Writing `equals` Step by Step
Assume you can write Java classes with fields and constructors, use object references, and understand method overriding. This chapter uses an immutable value class. An immutable object cannot change its equality-relevant fields after construction.
The equals method answers a business question: “Do these two objects represent the same value?” Its declaration comes from Object:
public boolean equals(Object other)The parameter must be Object. A method such as equals(Point other) is an overload, not an override, so collections will not call it.
The equality decision
A reliable implementation follows this order:
- Return
truewhen both references point to the same object. - Return
falsewhen the other reference isnull. - Check whether the other object has the allowed type.
- Cast the object to that type.
- Compare every field that defines the value.
This order is easy to read and handles common special cases before field access.
A complete implementation
This class uses instanceof. Because the class is final, no subclass can add another value field and create a symmetry problem.
import java.util.Objects;
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Point)) {
return false;
}
Point point = (Point) other;
return x == point.x && y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
public static void main(String[] args) {
Point first = new Point(3, 4);
Point second = new Point(3, 4);
Point different = new Point(4, 3);
System.out.println(first.equals(second)); // true
System.out.println(first.equals(different)); // false
System.out.println(first.equals(null)); // false
System.out.println(first.equals("3,4")); // false
}
}The @Override annotation asks the compiler to verify that the method overrides a superclass method. It catches a frequent mistake, such as declaring equals(Point other) instead of equals(Object other).
Choosing the type check
instanceof Point accepts a Point or an instance of a subclass. This can work when subclasses do not add equality-relevant state. However, a subclass that adds a field can make one direction of comparison return true and the other return `false.
getClass() requires the exact same runtime class:
if (other == null || getClass() != other.getClass()) {
return false;
}Use getClass() when exact class identity is part of the value definition. Use instanceof for a designed type hierarchy, and ensure subclasses preserve symmetry and transitivity. For simple value objects, a final class avoids this choice.
Exercise
What should equals return when it receives the same reference as this, and why should that check happen first?
Show answer
It should return true. The same object always represents the same value, and the check avoids unnecessary type and field comparisons.