Java equals() and hashCode() Contract in 2 min
Equals
Java equals() and hashCode() Contract in 2 min
Photo by Christopher Gower on Unsplash
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
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, dept
Interview One-Liner :
If two objects are equal according to equals(), they must have the same hashCode(). Otherwise, hash-based collections may behave incorrectly.
메타데이터
- post_id
- 76cc9f3c91c0
- slug
- java-equals-and-hashcode-contract-in-3-min-76cc9f3c91c0
- url
- https://medium.com/@debugbytez4tech/java-equals-and-hashcode-contract-in-3-min-76cc9f3c91c0
- canonical_url
- https://medium.com/@debugbytez4tech/java-equals-and-hashcode-contract-in-3-min-76cc9f3c91c0
- author_url
- https://medium.com/@debugbytez4tech
- status
- ok
- fetched_at
- 2026-06-28 04:42:08