Skip to content

๐Ÿง  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:

  1. Find bucket using hashCode()
  2. Compare using equals()

๐Ÿ“ฆ Example: Without overriding (Problem)

class Person {
    String name;
    int age;
}
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()

if (this == o) return true;

๐Ÿ‘‰ Same object in memory โ†’ obviously equal

if (o == null || getClass() != o.getClass()) return false;

๐Ÿ‘‰ Prevent null comparison and type mismatch

return age == person.age &&
       Objects.equals(name, person.name);

๐Ÿ‘‰ Compare actual fields (business logic)


๐Ÿงฎ hashCode()

return Objects.hash(name, age);

๐Ÿ‘‰ 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)