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

5 comments:

oakleyses said...

louis vuitton handbags, oakley sunglasses, louboutin, longchamp outlet, nike shoes, louis vuitton outlet stores, chanel handbags, burberry outlet, prada outlet, jordan shoes, tiffany and co, michael kors outlet, tory burch outlet, louis vuitton outlet, longchamp handbags, nike free, true religion jeans, michael kors outlet, kate spade outlet, polo ralph lauren outlet, tiffany and co, prada handbags, polo ralph lauren outlet, michael kors outlet, michael kors outlet, longchamp handbags, oakley sunglasses, ray ban sunglasses, kate spade handbags, burberry outlet, louis vuitton outlet, louboutin outlet, louboutin, coach factory outlet, air max, air max, coach outlet, gucci outlet, christian louboutin shoes, michael kors outlet, coach purses, ray ban sunglasses, michael kors outlet, louis vuitton, coach outlet store online, true religion jeans, oakley sunglasses cheap

oakleyses said...

ralph lauren, lululemon, air max, hollister, north face, nike air max, polo lacoste, vanessa bruno, timberland, vans pas cher, louboutin, louis vuitton, oakley pas cher, air max pas cher, nike roshe run, air max, true religion outlet, barbour, sac longchamp, air force, hollister, sac louis vuitton, nike free, polo ralph lauren, nike trainers, louis vuitton uk, nike roshe, sac hermes, longchamp, michael kors, sac burberry, sac guess, mulberry, new balance pas cher, converse pas cher, sac louis vuitton, hogan outlet, nike tn, north face, true religion outlet, ray ban pas cher, michael kors, air jordan, nike blazer, nike free pas cher, michael kors pas cher, abercrombie and fitch, ray ban sunglasses

oakleyses said...

mac cosmetics, mont blanc, marc jacobs, canada goose outlet, nike huarache, vans shoes, soccer jerseys, hollister, giuseppe zanotti, beats by dre, abercrombie and fitch, longchamp, insanity workout, celine handbags, bottega veneta, ghd, nfl jerseys, north face outlet, chi flat iron, ugg boots, birkin bag, ugg australia, canada goose, herve leger, ugg pas cher, rolex watches, valentino shoes, canada goose uk, canada goose, ferragamo shoes, canada goose, ugg boots, uggs outlet, north face jackets, soccer shoes, asics running shoes, new balance shoes, p90x, lululemon outlet, canada goose jackets, mcm handbags, instyler, babyliss pro, ugg, wedding dresses, jimmy choo outlet, reebok outlet, nike roshe run

oakleyses said...

parajumpers, karen millen, air max, converse, pandora charms, moncler, louboutin, moncler, links of london, lancel, juicy couture outlet, oakley, hollister, pandora charms, supra shoes, thomas sabo, canada goose, gucci, wedding dresses, timberland boots, swarovski crystal, air max, coach outlet store online, moncler, ray ban, canada goose, moncler, ugg, louis vuitton, swarovski, hollister, montre homme, moncler, hollister clothing store, ralph lauren, rolex watches, moncler outlet, moncler, iphone 6 cases, baseball bats, juicy couture outlet, toms shoes, vans, pandora jewelry, ugg, converse shoes

Zheng junxai5 said...

zhengjx20160721
nike roshe run
coach outlet
adidas yeezy
kobe shoes 11
louis vuitton bags
red bottom shoes
adidas running shoes
cheap jordan shoes
coach factory outlet
louis vuitton outlet
michael kors handbags
louis vuitton handbags
michael kors outlet
adidas outlet store
retro 11
nike outlet
instyler
adidas yeezy
coach outlet online
ray bans
coach factory outlet online
hermes birkin handbags
insanity workout
adidas wings
toms shoes
air jordan shoes
nike trainers women
burberry handbags
ralph lauren outlet
oakley sunglasses wholesale
nike roshe one
cheap rolex watches
louis vuitton outlet
michael kors outlet clearance
cheap ray ban sunglasses
nike store
cheap jerseys
adidas factory outlet
tiffany and co
ray ban outlet