FAQ
1. Is it mandatory to override equals and hashCode?
equals and hashCode?2. What if I just implement equals() and not hashCode()?
equals() and not hashCode()?class Employee {
int id;
Employee(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Employee)) return false;
Employee emp = (Employee) obj;
return this.id == emp.id;
}
}
public class Main {
public static void main(String[] args) {
HashSet<Employee> set = new HashSet<>();
Employee e1 = new Employee(1);
Employee e2 = new Employee(1);
set.add(e1);
set.add(e2);
System.out.println(set.size()); // Output: 2 ❌ (should be 1)
}
}3. What if I implement hashCode() but not equals()?
hashCode() but not equals()?4. Can two objects have the same hash code but not be equal?
5. Can two objects be equal but have different hash codes?
Last updated