equals and hashCode are a pair. Hash-based collections (HashMap, HashSet) place an object in a bucket with hashCode and find it again with equals. Break one, lose the other — silently.
x.equals(x)x.equals(y) iff y.equals(x)x.equals(null) is false, never NPEequals is true, hashes are equal.Definition: override both or neither. Use @Override on equals(Object). A method equals(MyType) is an overload and will not be called by the JDK collections.
| Kind | Equality | Typical types |
|---|---|---|
| Identity | == (Object.equals default) | Sockets, threads, mutable services, listeners |
| Value | Field-wise equals + hashCode | Money, Point, String, records, LocalDate |
| Entity | Stable id (DB key), often not equals on mutable fields | Customer with a changing email |
public final class Money {
private final long cents;
private final String currency;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Money m)) return false; // Java 16 pattern
return cents == m.cents && currency.equals(m.currency);
}
@Override
public int hashCode() {
return Objects.hash(cents, currency);
}
}
instanceof (and a final class) over getClass() unless you have a documented inheritance story. Mixing subclass equality with instanceof breaks symmetry (see Effective Java).== (except float/double — use Float.compare / Double.compare for NaN/−0.0).Objects.equals (null-safe).Arrays.equals / Arrays.hashCode (or deep variants). Default array equals is identity.Objects.hash is convenient, not maximal performance. Fine until measured otherwise.Incorrect:
public boolean equals(Money o) { // does not override
return o != null && cents == o.cents;
}
public int hashCode() { return 1; } // legal but turns HashMap into a list
Comparable / Comparator define order for TreeMap, TreeSet, and sort.
compareTo == 0 iff equals.TreeSet and HashSet disagree about “the same” element. Sorted maps can swallow entries.BigDecimal is the famous JDK example: 1.0 and 1.00 compareTo 0 but are not equals. Do not use BigDecimal as a TreeMap key without a Comparator that matches your equals.record Version(int major, int minor) implements Comparable<Version> {
public int compareTo(Version o) {
int c = Integer.compare(major, o.major);
return c != 0 ? c : Integer.compare(minor, o.minor);
}
}
Definition: an object is immutable if its observable state cannot change after construction. All fields are typically final, reference fields point at immutable types (or are defensively copied), and no method mutates.
Benefits: safe publication after a safe constructor; no defensive copies at API boundaries; trivial equals; thread-sharing without locks.
// Incorrect — mutable key
class Key { int id; }
Key k = new Key();
map.put(k, "v");
k.id = 9; // lost in the map — lookup uses a new hash bucket
// Correct — record / final fields
record Key(int id) {}
Records (Java 16): a restricted class. The compiler generates a canonical constructor, accessors (cents() not getCents), equals, hashCode, and toString from the state description. The class is implicitly final. You may compact-construct to validate.
public record Money(long cents, String currency) {
public Money {
if (cents < 0) throw new IllegalArgumentException("cents");
currency = Objects.requireNonNull(currency);
}
}
If a record component is a mutable list, the generated equals is shallow — callers can still mutate the list. Copy in the compact constructor (items = List.copyOf(items)).
Enums: a fixed set of instances. == is correct and preferred. You may add fields and methods. Do not construct enums with new. EnumSet / EnumMap are the specialized collections.
Sealed types (Java 17): a class or interface may permit only named subtypes. Useful so equals and switches can stay exhaustive. Not a replacement for the equals contract.
== for String/Integer.Arrays.equals.compare (NaN is not equal to itself with ==).@Data on a JPA entity — generated equals on all fields is often the wrong model.equals(Object) and hashCode together, or neither.instanceof + final, or a documented getClass strategy — do not mix.==. Strings: equals. Wrappers: equals.~ Good luck with your revision! ~