Equals and hashCode
What you will learn
Equality is a decision about which objects represent the same value. For a product identifier, two separately created objects can name the same product. Override equals and hashCode together so that lookup and duplicate detection use that decision consistently.
- Implement value equality for a final class.
- Check equal values, hash consistency and key lookup.
Use a fresh directory per example. Save as Main.java, compile with javac --release 21 Main.java, then run java Main. Only JDK standard-library dependencies are needed. List, Map and Set operations used here are brief previews of later collection chapters.
Make two product IDs represent the same value
import java.util.*;public class Main { static final class ProductId { private final String code; ProductId(String code) { this.code = Objects.requireNonNull(code); } @Override public boolean equals(Object other) { return other instanceof ProductId id && code.equals(id.code); } @Override public int hashCode() { return code.hashCode(); } } public static void main(String[] args) { ProductId a = new ProductId("P7"); ProductId b = new ProductId("P7"); ProductId c = new ProductId("P8"); System.out.println(a == b); System.out.println(a.equals(b)); System.out.println(a.hashCode() == b.hashCode()); System.out.println(a.equals(c)); }}Expected output:
falsetruetruefalseSeparate instances share the same code. Their equality and hash agree, although identity differs.
Rules and mental model
The inherited Object.equals compares identity. A custom value class can instead compare its meaningful fields. Equal objects must produce equal hash codes, but equal hash codes do not imply equal objects. An equality method should be reflexive, symmetric, transitive, consistent while relevant state is unchanged, and false for null. A final class makes it easier to avoid incompatible equality definitions across subclasses. In a hash-based map, a key is associated with a value; the hash helps locate candidates and equality distinguishes them. Keep equality-relevant key state stable while the key is stored. Map behavior is not specified if a key changes in a way that affects equality. Do not rely on a particular failure after such a mutation.
Look up a value with a new equivalent key
import java.util.*;public class Main { static final class ProductId { private final String code; ProductId(String code) { this.code = Objects.requireNonNull(code); } @Override public boolean equals(Object other) { return other instanceof ProductId id && code.equals(id.code); } @Override public int hashCode() { return code.hashCode(); } } public static void main(String[] args) { Map<ProductId, Integer> stock = new HashMap<>(); stock.put(new ProductId("P7"), 4); System.out.println(stock.get(new ProductId("P7"))); System.out.println(stock.containsKey(new ProductId("P8"))); System.out.println("Aa".hashCode() == "BB".hashCode()); System.out.println("Aa".equals("BB")); }}Expected output:
4falsetruefalseMap retrieval uses the key contract. The two strings demonstrate a real collision without being equal.
Common mistakes
Writing equals(ProductId) overloads rather than overrides equals(Object). Use @Override to let the compiler check the signature. Never compare only hash codes to establish equality.
Practice
Create a final ShelfId class with an int aisle field. Implement equals(Object) and hashCode. Insert an ID for aisle 2 into a HashSet, then check whether separately created IDs for aisles 2 and 3 are present and whether equality with null is false.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Equals and hashCode — knowledge check
Apply the chapter contracts and reason about Java 21-compatible examples.
Two distinct ProductId instances have the same code. What must be true?
Why can unequal strings have the same hash?
Which signature overrides Object equality?