Sobes.tech
Junior — Middle

Why can two objects with the same hashCode have different results when compared using equals?

sobes.tech AI

Answer from AI

In Java, the hashCode() method returns an integer value used for quick object lookup in hash-based structures, such as HashMap or HashSet. However, having the same hashCode does not guarantee that objects are equal.

The reason is that hashCode is just a hash function that can produce collisions, meaning different objects can have the same hash.

The equals() method defines the actual equality of objects based on their content or comparison logic.

Therefore, two objects can have the same hashCode, but when compared using equals(), they may return false if they differ in significant fields.

Example:

class Person {
    String name;
    int age;

    @Override
    public int hashCode() {
        return 42; // intentionally simple hash for example
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person p = (Person) o;
        return age == p.age && name.equals(p.name);
    }
}

Person p1 = new Person("Alice", 30);
Person p2 = new Person("Bob", 25);

System.out.println(p1.hashCode() == p2.hashCode()); // true
System.out.println(p1.equals(p2)); // false

It is important that when overriding equals(), you also override hashCode() so that equal objects have the same hash, but the reverse is not necessarily true.