Ch. 7 · Java

Java Equals and HashCode Collection Contracts

Java Equals and HashCode Collection Contracts. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readbeginnerupdated Oct 3, 2026

Equal objects must have equal hash codes. Hash-based collections use both hashing and equality, so overriding only one breaks their contract.

Before you start

You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.

The practical goal is to reason through this situation: Two logically equal customer keys should retrieve the same map entry. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Define logical equality

Select the immutable fields that identify the key.

Step 2: Implement both contracts

Equal keys must produce equal hashes; unequal keys may collide.

Step 3: Keep keys stable

Do not change equality fields after insertion into a map.

Worked scenario

Two logically equal customer keys should retrieve the same map entry.

Insert customer key A, then look up with separately created equal key B. Lookup should find the entry despite different object identities. If A’s identifying field changes afterward, its entry remains stored under the earlier hashing decision; a new lookup may search a different bucket.

Common mistake

Fields participating in equality can change after insertion and make a key difficult to find.

Verify the behavior

Test equal separate instances, unequal colliding keys and attempted key mutation.

Interview exercise

Design a stable key.

Answer and reasoning

Use immutable equality fields and implement equals and hashCode consistently; document whether identity or value equality is intended.

Continue learning

Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.

More in Java

read ✓Java · hard

Java Time Types and Zone-Aware Decisions

Java Time Types and Zone-Aware Decisions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Java · hard

Java Generics Wildcards and PECS

Use ? extends T for producers and ? super T for consumers, and understand why List<String> is not a List<Object>.

~2 min readread →
read ✓Java · easy

Java ArrayList Capacity and Performance

Java ArrayList Capacity and Performance. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc