๐ง Why do we need equals() and hashCode()?¶
equals()โ decides logical equality (are two objects โthe sameโ?)hashCode()โ decides which bucket the object goes into
๐ Hash-based collections use both:
- Find bucket using
hashCode() - Compare using
equals()
๐ฆ Example: Without overriding (Problem)¶
Person p1 = new Person("Swapnil", 25);
Person p2 = new Person("Swapnil", 25);
System.out.println(p1.equals(p2)); // โ false
๐ Why?
Default equals() from Object checks memory address, not values.
โ Correct Implementation¶
import java.util.Objects;
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true; // same reference
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
๐ Step-by-Step Explanation¶
๐งฉ equals()¶
๐ Same object in memory โ obviously equal
๐ Prevent null comparison and type mismatch
๐ Compare actual fields (business logic)
๐งฎ hashCode()¶
๐ Generates a number based on fields used in equals()
โ ๏ธ Rule:
If two objects are equal โ their hashCode must be equal
โ ๏ธ Important Contract (Interview Gold)¶
๐ Rule 1¶
If equals() is true โ hashCode() must be same
๐ Rule 2¶
If hashCode() is same โ equals() may or may not be true
๐ฅ What happens if you break it?¶
Set<Person> set = new HashSet<>();
set.add(new Person("Swapnil", 25));
set.add(new Person("Swapnil", 25));
๐ If not overridden properly:
- You may get duplicate entries ๐ฑ
๐ฏ Real Interview Answer¶
โequals() is used for logical comparison, while hashCode() is used by hash-based collections to determine bucket location. Both must be overridden together to maintain consistency and avoid unexpected behavior in collections like HashMap and HashSet.โ
๐ Memory Trick¶
Think of it like a library ๐:
hashCode()โ which shelf (fast lookup)equals()โ which exact book (final check)