Lesson 30: The equals(), hashCode() and toString() Contract

31 Jul 2026 1 min Swarnil Singhai

These three Object methods control how your objects behave in collections, debug output, and equality checks — get them wrong and HashMaps break.

Real-time example

A Product used as a HashMap key must override both equals and hashCode together, or two 'equal' products won't be found in the map.

class Product {
    String sku;
    Product(String sku) { this.sku = sku; }

    @Override public boolean equals(Object o) {
        return o instanceof Product p && p.sku.equals(sku);
    }
    @Override public int hashCode() { return sku.hashCode(); }
    @Override public String toString() { return "Product(" + sku + ")"; }
}

What's happening

HashMap uses hashCode() to find the bucket and equals() to confirm the match — override one without the other and lookups silently fail.

IDEs (and records) can auto-generate these — but understand the contract, don't just click 'generate'.

Advertisement