Sub topic 15
Testing `equals`, `hashCode`, and `toString` Contracts
Assume you can write and compile Java classes, use collections, and understand method overriding. This chapter uses plain Java assertions that throw AssertionError, so the example runs without a testing library.
Testing these methods means checking rules, not only checking one expected result. A good test uses several objects that should be equal, objects that should differ, and boundary values such as null.
What to test
The equals contract requires that equality be:
- Reflexive: an object equals itself.
- Symmetric: if
a.equals(b)is true, thenb.equals(a)is true. - Transitive: if
aequalsb, andbequalsc, thenaequalsc. - Consistent: repeated calls return the same result while the objects do not change.
- False for
null: a normal object never equalsnull.
The hashCode contract adds this rule: equal objects must have equal hash codes. Unequal objects may still have the same hash code, although many collisions can reduce collection performance.
A useful toString test checks that important state appears in a readable form. It should not usually assert the entire string unless the exact format is part of the public API.
| Test | Expected result |
|---|---|
| `a.equals(a)` | `true` |
| `a.equals(null)` | `false` |
| `a.equals(b)` and `b.equals(a)` | same result |
| Equal `a` and `b` | equal hash codes |
| `a.toString()` | contains useful state |
A complete contract test
The following program tests an immutable Point value class. The check method throws an error when a condition is false.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class ContractTest {
public static 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);
}
@Override
public String toString() {
return "Point{x=" + x + ", y=" + y + "}";
}
}
private static void check(boolean condition, String message) {
if (!condition) {
throw new AssertionError(message);
}
}
public static void main(String[] args) {
Point a = new Point(2, 3);
Point b = new Point(2, 3);
Point c = new Point(2, 3);
Point different = new Point(3, 2);
check(a.equals(a), "reflexivity failed");
check(a.equals(b) && b.equals(a), "symmetry failed");
check(a.equals(b) && b.equals(c) && a.equals(c),
"transitivity failed");
check(!a.equals(null), "null comparison failed");
check(a.equals(b), "consistency failed");
check(a.hashCode() == b.hashCode(),
"equal objects need equal hash codes");
check(!a.equals(different), "different points compared equal");
check(a.toString().contains("x=2"), "toString lost x");
Set<Point> points = new HashSet<>();
points.add(a);
check(points.contains(b), "HashSet lookup failed");
System.out.println("All contract checks passed.");
}
}The HashSet check is important because it tests both methods together. The set first uses hashCode to select a bucket, then uses equals to compare objects in that bucket. If either method is wrong, a logically equal point may not be found.
Test edge cases deliberately
Add cases for every field type your class uses:
- Test two
nullfields as equal and anullfield against a non-nullfield as unequal. - Test arrays by contents with
Arrays.equals, not with==. - Test floating-point values according to your chosen policy, often with
Double.compare. - Test that changing an object is impossible if it is intended to be a map or set key.
Exercise
A class overrides equals but not hashCode. Which test in this chapter is most likely to expose the defect?
Show answer
The equal-hash-code check or the HashSet lookup check. Equal objects can receive different identity-based hash codes, so the collection may search the wrong bucket.