FAQ
1. Is it mandatory to override equals and hashCode?
equals and hashCode?No, it is not mandatory to override equals() and hashCode(), but it is recommended when working with custom objects that will be used in collections like HashSet, HashMap, or HashTable.
By default, equals() and hashCode() are inherited from Object:
equals()compares object references (not values).hashCode()returns a unique integer for the object instance.
If you don't override them, two objects with the same data may be considered different in collections.
2. What if I just implement equals() and not hashCode()?
equals() and not hashCode()?If you override equals() but do not override hashCode(), our object may behave unexpectedly in hash-based collections.
Example:
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)
}
}Why?
equals()considerse1ande2equal.But since
hashCode()is not overridden,e1ande2may have different hash codes, soHashSettreats them as different objects.
3. What if I implement hashCode() but not equals()?
hashCode() but not equals()?If we override hashCode() but not equals(), two objects may have the same hash code but still be considered not equal.
Example:
Why?
Even though
hashCode()returns the same value,equals()still checks object references, which are different.This can cause incorrect behavior in
HashMap,HashSet, etc.
4. Can two objects have the same hash code but not be equal?
Yes, this is called a hash collision.
Example:
Why?
Since we forcefully return
100for all objects, different objects have the samehashCode.But
equals()differentiates them correctly.
5. Can two objects be equal but have different hash codes?
No, if two objects are equal, they must have the same hash code.
According to the contract of hashCode() and equals():
If
a.equals(b) == true, thena.hashCode() == b.hashCode()must also be true.
Example (Incorrect implementation breaking contract):
Why is this incorrect?
Since
equals()says two cars with the same model are equal, theirhashCode()must also be the same.But due to random hash generation, they have different hash codes, which violates the contract.
Last updated