Sub topic 4
Writing equals step by step
This chapter assumes you know how to write Java classes with fields and constructors, the difference between primitives and object references, and how method overriding works. It also assumes you have read the previous chapter on the equals contract: reflexive, symmetric, transitive, consistent, and false for null. Here you turn that contract into code, one step at a time.
The default and what you are replacing
Object.equals is defined as this == obj. Two references are equal only if they point to the same object. That is correct for classes where each instance is unique, such as a thread or a connection. It is wrong for value classes, where two instances with the same data should count as the same value.
Override equals only for value-like classes. If each instance is unique, keep the default.
The recipe
A correct equals for a final class follows five steps. The diagram shows the decision order.
- Declare the method as
public boolean equals(Object o)and add@Override. - Return
trueifthis == o. This is a cheap shortcut and satisfies reflexivity. - Return
falseifois not an instance of your class. - Cast
oto your class. - Compare every significant field and return the result.
Here is the recipe applied to an immutable value class:
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 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=" + x + ", y=" + y + "}";
}
public static void main(String[] args) {
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
System.out.println(a.equals(null)); // false
System.out.println(a.equals("1,2")); // false
}
}Each step has a reason.
Step 1: the signature and @Override
The parameter type must be Object. If you write equals(Point other), you create an overload, not an override. Collections call equals(Object), so they never reach your method. The @Override annotation turns this mistake into a compile error. Always write it.
Step 2: the identity shortcut
this == o returns true immediately when an object is compared with itself. This guarantees reflexivity. It also saves work when equals would otherwise compare many fields. It is an optimization, so leave it out if you prefer. Reflexivity still holds if the field comparison is correct.
Step 3: the type check and null
instanceof returns false when its left operand is null. So one instanceof check covers both null and wrong-type arguments. You do not need a separate o == null test. The contract says x.equals(null) must return false and must not throw a NullPointerException.
The type check also prevents a ClassCastException. The contract requires equals to return false for objects of unrelated classes, not to throw.
Step 4: the cast
After the instanceof check passes, the cast is safe. Cast once into a local variable instead of casting on every field access.
Step 5: field comparison
Compare each field that contributes to the logical value of the object. Which comparison to use depends on the field type:
| Field type | Comparison | Reason |
|---|---|---|
| `int`, `long`, `short`, `byte`, `char`, `boolean` | `==` | Primitives compare by value |
| `float`, `double` | `Float.compare` or `Double.compare` | Handles `NaN` and `-0.0` versus `0.0` |
| Object reference that may be `null` | `Objects.equals(a, b)` | Null-safe |
| Object reference that is never `null` | `a.equals(b)` | Cheaper, but throws if `a` is `null` |
| Array | `Arrays.equals(a, b)` | Compares contents, not references |
Comparing doubles with == has two problems. Double.NaN == Double.NaN is false, so an object holding NaN would not equal itself. And 0.0 == -0.0 is true, although the two values have different bit patterns and different Double.hashCode results. Double.compare treats NaN as equal to itself and -0.0 as less than 0.0, which keeps equals consistent with hashCode.
The next example puts all of these field types in one equals:
import java.util.Arrays;
import java.util.Objects;
public final class Sample {
private final String label; // may be null
private final double score;
private final int[] values;
public Sample(String label, double score, int[] values) {
this.label = label;
this.score = score;
this.values = values.clone();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Sample)) return false;
Sample s = (Sample) o;
return Objects.equals(label, s.label)
&& Double.compare(score, s.score) == 0
&& Arrays.equals(values, s.values);
}
@Override
public int hashCode() {
int result = Objects.hash(label, score);
return 31 * result + Arrays.hashCode(values);
}
public static void main(String[] args) {
Sample a = new Sample(null, Double.NaN, new int[] {1, 2});
Sample b = new Sample(null, Double.NaN, new int[] {1, 2});
System.out.println(a.equals(b)); // true
System.out.println(a.equals(a)); // true, even with NaN
}
}The constructor clones the array. Without the copy, a caller could change the array after construction and change the object's equality.
Order of comparisons
The && chain short-circuits, so put cheap comparisons and fields that most often differ first. Compare int fields before long strings or collections. The result is the same, but a mismatch is found sooner.
Which fields count
Include every field that is part of the object's logical value. Leave out derived fields, caches, and lazily computed values. If a field is excluded from equals, it must also be excluded from hashCode.
instanceof versus getClass
There are two common ways to do the type check in step 3.
if (!(o instanceof Point)) return false; // instanceof style
if (o == null || getClass() != o.getClass()) return false; // getClass style| Property | `instanceof` | `getClass()` |
|---|---|---|
| Subclass instances can equal a superclass instance | Yes | No |
| Preserves symmetry when subclasses add value fields | No | Yes |
| Preserves substitutability (Liskov) | Yes | No, a subclass is never equal to its parent |
| Needs a separate null check | No | Yes |
For a final class the two behave the same, because no subclass exists. That is why the Point example above is safe. If your class is not final, you must decide how subclasses should behave. A later chapter on equality across subclasses covers that choice in detail. For now, prefer final value classes.
Common mistakes in step-by-step implementations
- Forgetting
hashCode. Always override both together. A class withequalsand no matchinghashCodebreaksHashSetandHashMap. - Comparing arrays with
==or.equals. Both compare references. UseArrays.equals. - Calling
a.equals(b)on a field that may benull. UseObjects.equals. - Throwing an exception from
equals. Returnfalseinstead. - Including a mutable field. If the field changes after the object is stored in a hash collection, the object can be lost. Prefer immutable fields.
- Comparing fields in a way that depends on outside state, such as a file or a network lookup. The consistency rule requires repeated calls to return the same answer.
Checking your work
Before moving on, run through these questions for each equals you write:
- Does it have
@Overrideand anObjectparameter? - Does
x.equals(null)returnfalsewithout throwing? - Is every field in
equalsalso inhashCode, and the other way around? - Are
doubleandfloatfields compared withcompare, arrays withArrays.equals, and nullable references withObjects.equals? - Is the class
final, or have you decided deliberately how subclasses behave?
Exercise
A class Money has a long cents field and a String currency field that may be null. Write the body of equals(Object o) using the five-step recipe. Then say which comparison you use for each field and why.
Show answer
if (this == o) return true;
if (!(o instanceof Money)) return false;
Money m = (Money) o;
return cents == m.cents && Objects.equals(currency, m.currency);
cents is a primitive long, so == compares its value. currency may be null, so Objects.equals is used, because currency.equals(...) would throw a NullPointerException. The instanceof check also covers a null argument. The class should be final, and hashCode must use the same two fields.
Exercise
This class has a bug that makes list.contains(new Id(1)) return false for a list holding new Id(1). Identify the bug and fix it.
class Id {
final int value;
Id(int value) { this.value = value; }
public boolean equals(Id other) {
return other != null && value == other.value;
}
}
Show answer
The method takes an Id parameter, so it overloads equals instead of overriding equals(Object). List.contains calls equals(Object), which is still the identity-based default from Object. Fix it by changing the parameter type to Object, adding @Override, using instanceof and a cast, and adding a matching hashCode. For example: @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Id)) return false; return value == ((Id) o).value; } and @Override public int hashCode() { return Integer.hashCode(value); }.