If You Override equals() but Not hashCode() in Java?

In Java, the equals() and hashCode() methods work together to determine object equality, especially when objects are stored in collections such as HashMap or HashSet.


equals() Method

The equals() method is used to compare the logical equality of two objects.


public boolean equals(Object obj)

Example:


class Person {

    String name;

    Person(String name){
        this.name = name;
    }

    public boolean equals(Object obj){
        Person p = (Person) obj;
        return this.name.equals(p.name);
    }

}

hashCode() Method

The hashCode() method returns an integer value used by hash-based collections to locate objects quickly.


public int hashCode()

The Contract Between equals() and hashCode()

  • If two objects are equal using equals(), they must have the same hashCode()
  • If two objects have different hashCodes, they must not be equal
Whenever you override equals(), you should also override hashCode().

Problem Example

If equals() is overridden but hashCode() is not, collections like HashSet or HashMap may behave incorrectly.


class Person {

    String name;

    Person(String name){
        this.name = name;
    }

    public boolean equals(Object obj){
        Person p = (Person) obj;
        return this.name.equals(p.name);
    }

}

public class Test {

    public static void main(String[] args) {

        HashSet<Person> set = new HashSet<>();

        set.add(new Person("John"));
        set.add(new Person("John"));

        System.out.println(set.size());

    }

}
Expected output: 1
Actual output: 2

Even though the objects are logically equal, HashSet treats them as different because their hashCodes are different.


Correct Implementation


class Person {

    String name;

    Person(String name){
        this.name = name;
    }

    public boolean equals(Object obj){

        if(this == obj)
            return true;

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

        Person p = (Person) obj;

        return name.equals(p.name);
    }

    public int hashCode(){
        return name.hashCode();
    }

}
Now HashSet and HashMap will correctly detect duplicate objects.

Real World Example

Consider a system storing users in a HashSet. If equals() is overridden but hashCode() is not, duplicate users may appear in the collection.

  • User registration systems
  • Cache keys
  • Session management

Incorrect equality logic can lead to duplicate data or memory issues.


Quick Summary

  • equals() checks logical equality
  • hashCode() determines object bucket in hash collections
  • If equals() is overridden, hashCode() must also be overridden
  • Otherwise HashMap and HashSet may behave incorrectly

0 comments

Leave a comment