Module 7 · Core Java APIs — topic 3 of 4
equals, hashCode and toString
The methods every class inherits from Object, how to override equals and hashCode correctly together, why it matters for HashSet and HashMap, and the Objects helper class.
Learning objectives
- Override equals following its contract
- Override hashCode consistently with equals
- Use java.util.Objects helpers
Definition
java.lang.Object is the root of every class. Its methods equals (logical equality), hashCode (an integer used by hash-based collections) and toString (a text description) are meant to be overridden; equal objects must always have equal hash codes.
Introduction
Two Point objects with the same coordinates should probably be 'equal', but Java can't know that unless you say so. By default equals is identity (==) and hashCode is based on the object's identity. For value-like classes you must override both — and they must agree, or HashSet and HashMap stop working.
Why it matters
HashMap and HashSet — the most used collections — rely completely on equals and hashCode.
A broken equals/hashCode pair causes 'impossible' bugs: an object you just added to a set can't be found.
Detailed explanation
toString() returns ClassName@hexHash by default. Override it to show the important fields.
The equals contract. It must be *reflexive* (x.equals(x)), *symmetric*, *transitive*, *consistent* (same answer while fields don't change) and return false for null. The parameter type must be Object, otherwise you overload instead of override.
A standard equals. Return true for the same reference; return false if the argument is null or of a different class; cast and compare the significant fields — primitives with ==, objects with Objects.equals (null-safe), doubles with Double.compare.
The hashCode contract. Equal objects must have equal hash codes. Unequal objects may share a hash code, but fewer collisions mean faster maps. The easiest correct implementation is Objects.hash(field1, field2, ...).
Why both. A HashSet first uses hashCode to pick a bucket, then equals to compare within it. Override only equals and two equal objects may land in different buckets, so contains fails.
Mutable keys. If a field used in hashCode changes while the object is inside a HashSet or used as a HashMap key, the object becomes unfindable. Use immutable fields for equality — records do this automatically.
Other Object methods include getClass(), and the thread-related wait/notify. finalize is deprecated; use try-with-resources for clean-up.
Syntax
- equals must take Object, not your class.
- Use the same fields in equals and hashCode.
- Objects.equals(a, b) handles nulls safely.
Code examples
Default behaviour versus overriding
Plain equal? false, toString starts with: true Point equal? true false false same hash: true, toString: (1, 2)
Objects helpers
false true (none) default true name must not be null
More examples
What goes wrong in a HashSet without hashCode
bad contains equal key: false bad size after adding a duplicate: 2 good contains equal key: true good size after adding a duplicate: 1 mutable key still found: false
Step-by-step explanation
- BadKey overrides equals but not hashCode, so two equal keys usually get different identity-based hash codes and land in different buckets.
- That is why
containsfails and a 'duplicate' is accepted, breaking the rule that a set holds no duplicates. - GoodKey bases hashCode on the same field as equals, so the set behaves correctly.
o instanceof GoodKey k && ...is a compact equals using pattern matching; it also returns false for null.- Changing
m.codeafter insertion changes its hash code, so the set looks in the wrong bucket and can no longer find the object — use immutable fields as keys.
Expected output
Running “What goes wrong in a HashSet without hashCode” prints exactly:
Practical applications
- Entity and value classes used as HashMap keys or stored in HashSets
- De-duplicating records loaded from files or databases
- Unit tests that compare expected and actual objects with assertEquals
Best practices
- Override equals and hashCode together, using the same fields.
- Base equality on immutable fields.
- Let your IDE generate them, or use a record.
Common mistakes
Wrong equals signature
Avoid
Prefer
Taking Point creates an overload; collections call equals(Object), which still uses identity.
Overriding equals but not hashCode
Avoid
Prefer
Equal objects would have different hash codes, breaking HashMap and HashSet.
Important notes
getClass() != o.getClass()makes subclasses unequal to their parents;instanceofallows them — choose deliberately and keep equals symmetric.- Records automatically implement equals, hashCode and toString from their components.
Key takeaways
- equals defines logical equality and must accept Object.
- Equal objects must have equal hash codes; use Objects.hash.
- Mutable fields used in hashCode break hash-based collections.
Try it yourself
- 1Write equals and hashCode for a
Bookidentified by its ISBN, and prove a HashSet removes duplicates. - 2Show that a
TreeSetuses compareTo rather than equals by giving a class inconsistent methods.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
6 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerIf you override equals, what must you also override?
- BeginnerWhich signature correctly overrides Object.equals?
- ModerateWhat is printed?