Sunday, October 27, 2013

What issues / pitfalls must be considered when overriding equals and hashCode?
share|improve this question

24 Answers

up vote468down voteaccepted

The theory (for the language lawyers and the mathematically inclined):

equals() (javadoc) must define an equality relation (it must be reflexivesymmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.
hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).
The relation between the two methods is:
Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().

In practice:

If you override one, then you should override the other.
Use the same set of fields that you use to compute equals() to compute hashCode().
Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Langlibrary. An example:
public class Person {
    private String name;
    private int age;
    // ...

    public int hashCode() {
        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
            // if deriving: appendSuper(super.hashCode()).
            append(name).
            append(age).
            toHashCode();
    }

    public boolean equals(Object obj) {
        if (obj == null)
            return false;
        if (obj == this)
            return true;
        if (!(obj instanceof Person))
            return false;

        Person rhs = (Person) obj;
        return new EqualsBuilder().
            // if deriving: appendSuper(super.equals(obj)).
            append(name, rhs.name).
            append(age, rhs.age).
            isEquals();
    }
}

Also remember:

When using a hash-based Collection or Map such as HashSetLinkedHashSetHashMapHashtable, orWeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.
share|improve this answer
6 
"Furthermore, o.equals(null) must always yield false if o is an object"... well, if o is not an object, you have a NullPointerException thrown. –  Software Monkey Mar 11 '09 at 17:57
4 
Granted, that was a bit superfluous statement (following the style of the original javadoc for Object.equals(): "For any non-null reference value x, x.equals(null) should return false") –  Antti Sykäri May 28 '09 at 18:59
4 
Additional point about appendSuper(): you should use it in hashCode() and equals() if and only if you want to inherit the equality behavior of the superclass. For instance, if you derive straight from Object, there's no point because all Objects are distinct by default. –  Antti Sykäri May 28 '09 at 19:03
77 
You can get Eclipse to generate the two methods for you: Source > Generate hashCode() and equals(). – Darthenius Nov 22 '11 at 18:58
4 
show 7 more comments

No comments: