Java equals() and hashCode() Contract in 2 min
2 min readDec 15, 2025
Press enter or click to view image in full size![]()
Equals
equals()method is used to compare logical equality of objects- Default implementation (from
Objectclass) compares references - To compare object data, we must override
equals()
Example
import java.util.Objects;
public class Employee {
private int id;
private String name;
private int age;
private String dept;
public Employee(int id, String name, int age, String dept) {
this.id = id;
this.name = name;
this.age = age;
this.dept = dept;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Employee other = (Employee) obj;
return this.id == other.id
&& this.age == other.age
&& Objects.equals(this.name, other.name)
&& Objects.equals(this.dept, other.dept);
}
}Runner Class
public class Main {
public static void main(String[] args) {
Employee e1 = new Employee(1, "sagar", 26, "A");
Employee e2 = new Employee(1, "sagar", 26, "A");
Employee e3 = new Employee(2, "sagar", 26, "B");
System.out.println(e1 == e2); // false (reference check)
System.out.println(e1.equals(e2)); // true (value check)
System.out.println(e1.equals(e3)); // false (value check)
}
}hashCode
- Whenever we override
equals(), we must overridehashCode() - Hash-based collections (
HashSet,HashMap) rely onhashCode() - If not overridden, duplicate logical objects may get stored
Get DebugBytez’s stories in your inbox
Join Medium for free to get updates from this writer.
Issue Example (without hashCode())
HashSet<Employee> set = new HashSet<>();
set.add(e1);
set.add(e2);
System.out.println(set.size()); // 2 ❌Solution (Override hashCode())
// Overriding in Employee Class
@Override
public int hashCode() {
return Objects.hash(id, name, age, dept);
}After Fix
HashSet<Employee> set = new HashSet<>();
set.add(e1);
set.add(e2);
System.out.println(set.size()); // 1 ✅Important Contract Rule
Fields used in equals() and hashCode() must be the same
❌ Wrong
equals() → id, name, dept
hashCode() → id, name, age, dept✅ Correct
equals() → id, name, age, dept
hashCode() → id, name, age, deptInterview One-Liner :
If two objects are equal according to equals(), they must have the same hashCode(). Otherwise, hash-based collections may behave incorrectly.






