Sub topic 9
Writing equals with a pattern
This chapter assumes you can write a basic equals and hashCode pair, know the equals contract, and have read the earlier chapters on type patterns, binding variables, flow scoping, and null handling. It uses Java 16 or later, where pattern matching for instanceof is a standard feature.
What equals has to do
The equals contract in java.lang.Object requires five properties:
- Reflexive:
x.equals(x)is true. - Symmetric:
x.equals(y)andy.equals(x)give the same answer. - Transitive: if
x.equals(y)andy.equals(z)are true, thenx.equals(z)is true. - Consistent: repeated calls give the same answer while the objects do not change.
- Null-safe:
x.equals(null)is false and never throws.
A typical equals has three steps: check the type, cast, and compare fields. Before Java 16 the type check and the cast were two separate pieces of code that had to agree. A type pattern merges them.
The traditional form
This version tests the type, repeats the type in a cast, and declares a second variable:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point)) return false;
Point p = (Point) o;
return x == p.x && y == p.y;
}The class name Point appears twice. If you rename the class or change one occurrence, the compiler catches some mistakes but not all.
The pattern form
A type pattern removes the cast and the separate declaration. The simplest version is a single expression:
@Override
public boolean equals(Object o) {
return o instanceof Point p && x == p.x && y == p.y;
}Evaluation goes left to right, and each step runs only if the previous one was true:
o instanceof Point pis false whenoisnullor not aPoint. The whole expression is then false and the rest is skipped.- When it is true,
pis bound toowith static typePoint. x == p.xandy == p.ycompare the fields.pis in scope here because&&only evaluates its right side when the left side matched.
The early-return style
Real classes often have more fields, and a single long && chain gets hard to read. You can use the negation pattern from the earlier chapter instead. The guard returns early, so p is in scope for the rest of the method:
import java.util.Objects;
public final class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person p)) return false;
return age == p.age && Objects.equals(name, p.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public static void main(String[] args) {
Person a = new Person("Ada", 36);
Person b = new Person("Ada", 36);
System.out.println(a.equals(b)); // true
System.out.println(a.equals(null)); // false
System.out.println(a.equals("Ada")); // false
System.out.println(a.equals(a)); // true
}
}The this == o line is optional. It is a fast path for the common case of comparing an object with itself, and it does not change the result.
Comparing fields correctly
The pattern only replaces the type check and the cast. Field comparison still follows the usual rules:
| Field type | Compare with |
|---|---|
| `int`, `long`, `boolean`, `char` | `==` |
| `double` | `Double.compare(a, b) == 0` |
| `float` | `Float.compare(a, b) == 0` |
| Reference that may be `null` | `Objects.equals(a, b)` |
| Array | `Arrays.equals(a, b)` |
Use Double.compare rather than == because it treats NaN as equal to itself and distinguishes 0.0 from -0.0. This matches what Double.equals does, and hashCode stays consistent with it.
Null needs no special case
instanceof is false for null, with or without a pattern. The pattern-based equals therefore returns false for null without a separate check. This satisfies the null rule in the contract. You do not need if (o == null) return false;.
The getClass() idiom works differently. o.getClass() throws a NullPointerException when o is null, so code that uses it needs the explicit null check first.
Final classes versus inheritance
The instanceof test is true for the class and all its subclasses. This affects symmetry when the class is not final. The following program shows the problem:
public class SymmetryDemo {
static class Point {
final int x, y;
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; }
}
static class ColorPoint extends Point {
final String color;
ColorPoint(int x, int y, String color) {
super(x, y);
this.color = color;
}
@Override
public boolean equals(Object o) {
return o instanceof ColorPoint c
&& x == c.x && y == c.y && color.equals(c.color);
}
@Override
public int hashCode() { return 31 * super.hashCode() + color.hashCode(); }
}
public static void main(String[] args) {
Point p = new Point(1, 2);
ColorPoint cp = new ColorPoint(1, 2, "red");
System.out.println(p.equals(cp)); // true
System.out.println(cp.equals(p)); // false
}
}p.equals(cp) is true, because a ColorPoint is a Point with the same coordinates. cp.equals(p) is false, because p is not a ColorPoint. That breaks symmetry. The pattern did not cause this. The traditional instanceof plus cast has the same flaw.
You have three ways to handle it:
- Make the class
final. No subclass can exist, so the problem cannot arise. This is the best choice for value classes. - Use
getClass() != o.getClass()and cast. Instances of different classes are never equal. This keeps symmetry but gives up substitutability, and it cannot use a type pattern directly. - Define equality only in the base class and make
equalsfinal there. Subclasses then cannot add state that takes part in equality.
For a class you plan to keep non-final, choose option 2 or 3 deliberately and document it.
Scope mistakes to avoid
The scope rules from the earlier chapters apply here. The mistakes that actually occur in equals are these:
- Using
||to combine the type check with a field check. Writingo instanceof Point p || x == p.xdoes not compile, becausepis not definitely matched when the right side runs. - Forgetting the early return. In
if (!(o instanceof Person p)) { log(); }with noreturn, the body can complete normally.pis then not in scope after theif, and the compiler reports an error on the next line that uses it. - Reusing a name. A binding variable cannot have the same name as a local variable or parameter that is already in scope. If the method has a parameter called
other, do not name the patternother.
The hashCode companion
Whenever you override equals, override hashCode so that equal objects have equal hash codes. The pattern change does not affect hashCode. Compute it from the same fields that equals compares:
@Override
public int hashCode() {
return Objects.hash(name, age);
}Objects.hash boxes primitive values and allocates an array, which is fine for most code. In a performance-sensitive class, compute the hash by hand, as the Point example does.
When you do not need to write equals at all
A record generates equals, hashCode, and toString from its components:
record Coordinate(int x, int y) {}Two Coordinate values are equal when their components are equal. Use a record for plain data holders, and write equals by hand when the class has mutable state, hidden fields, or custom equality rules.
Exercise
Rewrite this equals method using a type pattern, keeping the behavior identical. Then say whether it still returns false for null. public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof Account)) return false; Account a = (Account) o; return id == a.id && Objects.equals(owner, a.owner); }
Show answer
Use the early-return form:
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Account a)) return false;
return id == a.id && Objects.equals(owner, a.owner);
}
It still returns false for null. The o == null test is redundant, because instanceof is already false for null. The binding variable a is in scope after the if, because the body returns and cannot complete normally.
Exercise
A non-final class Shape uses return o instanceof Shape s && name.equals(s.name);. A subclass Circle overrides equals to also compare a radius. Which contract property can break, and what is the simplest fix if you control both classes?
Show answer
Symmetry can break. A plain Shape can be equal to a Circle with the same name, but the Circle's equals returns false for the plain Shape. The simplest fix is to make equality a single definition: either make the classes final where possible, or use getClass() comparison so objects of different classes are never equal.