Sub topic 9
Writing `equals` with a Pattern
The usual job of `equals`
An equals method compares an object with another value and returns true when they represent the same value. A typical implementation must:
- Return
falsewhen the other value has the wrong type. - Compare the relevant fields.
- Return
falsefornull. - Provide a matching
hashCodeimplementation.
Before pattern matching, the type check and cast required separate steps:
@Override
public boolean equals(Object o) {
if (!(o instanceof Point)) {
return false;
}
Point other = (Point) o;
return x == other.x && y == other.y;
}The variable other is created only after the type test succeeds. The type appears twice: once in instanceof and again in the cast.
The pattern-based version
A type pattern combines the test and cast:
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 o) {
return o instanceof Point p
&& x == p.x
&& y == p.y;
}
@Override
public int hashCode() {
return 31 * 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, 4);
System.out.println(first.equals(second)); // true
System.out.println(first.equals(different)); // false
System.out.println(first.equals(null)); // false
}
}In o instanceof Point p:
ois tested to see whether it refers to aPoint.pis the binding variable.- When the test succeeds,
phas typePoint. - The
&&expressions run only after the pattern matches.
The expression is also safe for null. instanceof always returns false for null, so the field comparisons are never evaluated.
Choosing `instanceof` or `getClass`
The pattern-based form uses instanceof, which accepts instances of subclasses too. That choice works well for a final class such as Point, because no class can extend it.
For a non-final class, decide whether instances of subclasses should be equal to instances of the parent class. Using instanceof can cause problems when a subclass adds state or defines its own equals method. In such hierarchies, an exact-class check may be safer:
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) {
return false;
}
Point other = (Point) o;
return x == other.x && y == other.y;
}This version rejects every object whose runtime class differs. It cannot use a Point pattern unless the class check establishes that exact type in a way the compiler can flow-scope.
Common errors
Do not compare only the type:
return o instanceof Point;That says every Point is equal to every other Point, regardless of its coordinates.
Also keep hashCode consistent with equals. If two points are equal, their hash codes must be equal. Use the same fields in both methods.
Exercise
What does new Point(1, 2).equals(new Point(1, 3)) return, and why?
Show answer
It returns false because both objects match the Point pattern, but their y fields differ.