Java · Object equality

Java equals and hashCode interview question

A HashMap lookup depends on how a key defines equality. A good interview answer connects the equals and hashCode contract to what happens when you store and retrieve an object.

Published by RoleHello. References are linked in the guide.

Why must equals and hashCode agree in Java?

If two objects are equal according to equals, they must return the same hashCode. The reverse is not required: different objects can share a hash code. That is a collision, and a hash-based collection still needs equality checks to distinguish the keys.

For object references, == checks whether both references point to the same object. The default Object.equals also uses identity. A class can override equals to compare values, but it must then provide a matching hashCode implementation.

A HashMap uses the hash to locate a bucket and compares keys within that bucket. If you override equals while keeping an incompatible hash code, a lookup with an equal object can fail. Two objects representing the same customer may be treated as different keys.

For a simple value key, a Java record can generate both methods from its components:

import java.util.HashMap;
import java.util.Map;

record CustomerKey(String tenantId, String customerId) {}

class CustomerLookup {
    public static void main(String[] args) {
        Map<CustomerKey, String> names = new HashMap<>();
        names.put(new CustomerKey("north", "42"), "Maya");

        // A separate record instance with equal component values.
        System.out.println(names.get(new CustomerKey("north", "42")));
    }
}

This prints Maya. Both string components take part in the generated equality and hash code. Records are available in Java 16 and later.

Keep the data used for equality stable while the key is in the map. Changing a mutable key after insertion can leave it stored under its old hash, so a later lookup may miss it. Record components are final, but a record containing a mutable list would still need care. This example uses immutable strings.

In an interview, explain which fields identify the value and why those fields should remain stable. A correct implementation needs more than a convenient IDE-generated method.

Technical references