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.
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.
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
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."
Last updated: 16 July 2026
Previous question: What are the potential issues with using mutable objects as keys in a HashMap?
Next question: What is the difference between HashMap and IdentityHashMap in terms of how they handle keys?