What would happen if you override only the equals() method and not hashCode() in a custom key class used in HashMap?

When a class is used as a key in a HashMap, both equals() and hashCode() must follow a consistent contract. If you override only equals() and leave hashCode() unchanged, two logically equal objects may generate different hash codes. As a result, HashMap can place them in different buckets, causing lookup, retrieval, and duplicate key issues.

Key Points:

• HashMap first uses hashCode() to determine the bucket location of a key. • equals() is used only after locating the bucket to identify the exact key. • Equal objects must always return the same hash code. • Overriding equals() without hashCode() violates the Java contract and leads to unexpected behavior.

Example:

Suppose two Employee objects have the same employeeId and are considered equal by equals(). If hashCode() is not overridden, HashMap may store them in different buckets. Later, retrieving the value using an equivalent Employee object may fail even though the key appears to exist.

Code Example:

class Employee {

    private int id;

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Employee)) return false;

        Employee other = (Employee) obj;
        return this.id == other.id;
    }

    // hashCode() not overridden
}

HashMap<Employee, String> map = new HashMap<>();

Employee e1 = new Employee(101);
Employee e2 = new Employee(101);

map.put(e1, "John");

System.out.println(map.get(e2)); // May return null

Interview Tip:

A concise interview answer is: "If equals() is overridden but hashCode() is not, equal objects may produce different hash codes and be stored in different HashMap buckets. This breaks key lookup behavior, so equals() and hashCode() should always be overridden together."