0

I understand the basic concept of overriding hashcode and equals in a class , But can anyone give me an example (code) where the equals will fail only because hashcode was not overridden ? Thanks in advance.

Mr A
  • 27
  • 1
  • 5
  • 1
    You won't have that kind of code. equals cannot fail because hashcode is not overridden. – mael Jul 15 '13 at 20:02

2 Answers2

5

It's not that equals itself will fail - it's that anything that relies on the contract of hashCode and its relationship to equals could fail. Here's an example:

import java.util.*;

final class Person {
    private final String name;

    public Person(String name) {
        // TODO: Nullity prohibition
        this.name = name;
    }

    @Override
    public boolean equals(Object other) {
        if (other == null || other.getClass() != Person.class) {
            return false;
        }
        return name.equals(((Person)other).name);
    }
}

class Test {
    public static void main(String[] args) throws Exception {
        Person p1 = new Person("Jon");
        Person p2 = new Person("Jon");
        System.out.println(p1.equals(p2)); // true

        Set<Person> people = new HashSet<Person>();
        people.add(p1);
        people.add(p2);
        System.out.println(people.size()); // 2!
    }
}

HashSet assumes that because p1.hashCode() isn't the same as p2.hashCode(), the two elements must be unequal, so can both be in the set. That wouldn't happen if hashCode() were appropriately overridden.

Likewise you could have (with the same Person class);

Map<Person, String> map = new HashMap<Person, String>();
map.put(p1, "foo");
System.out.println(map.get(p2)); // null

This would print out "foo" if the two objects returned equal hash codes, as they're meant to - but again, because they don't, the HashMap thinks there's no match.

Eric Lippert's blog post on GetHashCode is a good introduction to this - it's C#-based, but it applies equally to Java.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
0

If your equals is failing it is because you implemented equals wrong.

Here is how to do it correctly: the answer to What issues should be considered when overriding equals and hashCode in Java?.

but, just for fun here is an example of an equals method that will fail if hashcode is not overridden:

//NEVER DO THIS
@Override
public boolean equals(Object o){
    ThisObject obj = (ThisObject)o;
    return this.hashCode() == obj.hashCode();
}
Community
  • 1
  • 1
Brinnis
  • 856
  • 5
  • 12