Saturday, December 7, 2013

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

24 Answers

up vote508down 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
7 
"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
5 
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
90 
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
There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate. If you didn't think this was unreasonably complicated already!
Lazy loaded objects are subclasses
If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means thatthis.getClass() == o.getClass() will return false. For example:
Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy
If you're dealing with an ORM using o instanceof Person is the only thing that will behave correctly.
Lazy loaded objects have null-fields
ORMs usually use the getters to force loading of lazy loaded objects. This means that person.namewill be null if person is lazy loaded, even if person.getName() forces loading and returns "John Doe". In my experience, this crops up more often in hashCode and equals.
If you're dealing with an ORM, make sure to always use getters, and never field references inhashCode and equals.
Saving an object will change it's state
Persistent objects often use a id field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in hashCode. But you can use it inequals.
A pattern I often use is
if (this.getId() == null) {
    return this == other;
} else {
    return this.getId() == other.getId();
}
But: You cannot include getId() in hashCode(). If you do, when an object is persisted, it'shashCode changes. If the object is in a HashSet, you'll "never" find it again.
In my Person example, I probably would use getName() for hashCode and getId plusgetName() (just for paranoia) for equals. It's okay if there are some risk of "collisions" forhashCode, but never okay for equals.
hashCode should use the non-changing subset of properties from equals
share|improve this answer
 
@Johannes Brodwall: i don't understand Saving an object will change it's statehashCode must return int, so how will you use getName()? Can you give an example for your hashCode –  jimmybondyNov 1 '12 at 14:14
 
@jimmybondy: getName will return a String object which also has a hashCode which can be used – mateusz.fiolka Mar 2 at 13:15
add comment
If you are using Eclipse it has integrated a very cool hashCode() / equals() generator.
You just have to be on a class and do: right click > Source code > Generate hashCode() andequals()...
Then, a window will show up and you can choose the fields to include in your methods.
share|improve this answer
5 
If you are using NetBeans, you can use Alt + Ins to bring up the Generate menu. –  Brian DiCasa Jul 23 '11 at 14:53
9 
It is easier in many cases but you still need to understand the reasons for this as the code generated is not always the best to use. –  Mark Aug 22 '12 at 13:43
1 
In Intellij-IDEA, with the editor focused go to Code -> Generate -> Override Hashcode and Equals. Follow the wizard. Enjoy. (cmd+N for Mac users, Control+N for the rest) –  Martín Marconcini Oct 25 at 20:20 
add comment

No comments: