Equals & HashCodeIntermediate
1Question 1 of 1
javaWhy must you override both equals() and hashCode() together in Java?
Explanation & Concept
The contract between `equals()` and `hashCode()` states that: **if two objects are equal according to equals(), they MUST have the same hashCode()**.
If you override `equals()` without overriding `hashCode()`, hash-based collections like `HashMap` and `HashSet` will store duplicates or fail to find existing keys because they check hash bucket placement first.
Code Example
java
import java.util.Objects;
public class EmployeeId {
private final String department;
private final int number;
public EmployeeId(String department, int number) {
this.department = department;
this.number = number;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof EmployeeId other)) return false;
return number == other.number && Objects.equals(department, other.department);
}
@Override
public int hashCode() {
return Objects.hash(department, number);
}
}How It Works & Key Takeaways
By hashing both `department` and `number`, two distinct object instances with identical field values produce the exact same hash code and resolve to the same `HashMap` bucket.
Mock Test · 1 Questions · Optional
Ready for Design Patterns?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions