Sub topic 3
Writing `equals` with Java Pattern Matching for `instanceof`
Assume you know basic Java classes, inheritance, casts, Boolean operators, and the usual equals contract.
Writing `equals` with a pattern
A type pattern makes an equals method shorter. The pattern tests the type and binds the value as a Point. Because Point is final, this implementation has predictable equality behavior.
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) {
return other instanceof Point p
&& x == p.x
&& y == p.y;
}
@Override
public int hashCode() {
return 31 * x + y;
}
}The expression returns false when other is null, when it has another type, or when either coordinate differs.
Common scope mistakes
A binding variable has a flow scope. The compiler allows p only where the pattern is known to have matched.
With &&, the right side runs only after the left side succeeds:
return other instanceof Point p && x == p.x;With ||, the right side might run after the pattern fails, so the variable is unavailable:
// Does not compile:
// return other instanceof Point p || p.x == 0;Negation can work with an early exit:
if (!(other instanceof Point p)) {
return false;
}
return x == p.x;Patterns and generic types
Java permits a parameterized type pattern when the test is type-safe. For example, this is valid because the source already has String elements:
static int size(java.util.Collection<String> values) {
if (values instanceof java.util.List<String> list) {
return list.size();
}
return 0;
}An Object cannot safely be tested as List<String> because Java cannot check the type argument at runtime. Use a reifiable type such as List<?>, then inspect elements separately.
Which Java version you need
Type patterns for instanceof became final in Java 16.
| Feature | Final Java version |
|---|---|
| `instanceof` type patterns | 16 |
| Record patterns and pattern `switch` | 21 |
Next step: record patterns
Java 21 can also extract record components:
record Point(int x, int y) {}
static String describe(Object value) {
if (value instanceof Point(int x, int y)) {
return x + "," + y;
}
return "not a point";
}Where this leads: patterns in `switch`
Pattern matching for switch applies the same idea to multiple alternatives. Each case can test a type and bind a variable, making type-based branching more direct.
Exercise
Why is p available after instanceof Point p on the left side of &&, but not after ||?
Show answer
&& evaluates its right side only when the pattern matched. || can evaluate its right side when the pattern failed.