Sub topic 3
Java equals, hashCode, and toString: Writing a useful `toString`
Assume you can write Java classes, use List, Set, and Map, and understand inheritance and overriding.
Writing a useful `toString`
toString() returns a text description of an object. The default implementation usually contains the class name and an identity hash in hexadecimal, which is rarely useful for logs or debugging.
Include the type and important state. Omit secrets such as passwords and access tokens.
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 String toString() {
return "Point{x=" + x + ", y=" + y + "}";
}
}A useful representation is stable, readable, and does not change the object.
Fields that need special handling
Use Objects.equals for nullable object fields, Double.compare for floating-point values, and Arrays.equals for array contents. Plain array comparison checks references, not elements. Use Arrays.hashCode in the matching hashCode() implementation.
Mutable keys
Hash-based collections use hashCode() to choose a bucket and equals() to find a matching key. If a key changes after insertion, its new hash may point to another bucket. The entry remains present, but lookup can fail.
Prefer immutable keys. If a key contains a mutable list or array, make a defensive copy and do not expose mutable state.
Overload versus override
equals(Value other) is an overload, not an override. Collections call equals(Object), so the custom method is ignored. Always write @Override; the compiler then catches this mistake.
Equality and subclasses
An instanceof comparison permits equality with subclasses, but subclass fields can break symmetry. A base object might equal a subclass while the subclass rejects the base object. getClass() avoids that problem by requiring the exact same class. Composition, where a class contains another value instead of extending it, often gives clearer equality rules.
Records
A record automatically generates equals(), hashCode(), and toString() from its components:
public record Point(int x, int y) {}Use records for immutable data carriers when their generated value-based behavior matches your design.
Testing the contracts
Test reflexivity, symmetry, transitivity, consistency, and inequality with null. Also test that equal objects have equal hash codes, unequal objects behave correctly in HashSet, and toString() contains useful state.
Exercise
Why can a mutable object become unreachable in a HashMap after it is used as a key?
Show answer
Mutating the key can change its hash code, so lookup searches a different bucket from the one containing the entry.