What issues / pitfalls must be considered when overriding equals and hashCode?

11 comments

@Johannes Brodwall 2008-11-02 02:58:13

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:

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.name will 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 in hashCode() and equals().

Saving an object will change its 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 in equals().

But: you cannot include getId() in hashCode(). If you do, when an object is persisted, its hashCode 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() plus getName() (just for paranoia) for equals(). It's okay if there are some risk of "collisions" for hashCode(), but never okay for equals().

hashCode() should use the non-changing subset of properties from equals()

@jimmybondy 2012-11-01 14:14:08

@Johannes Brodwall: i don't understand Saving an object will change it's state! hashCode must return int, so how will you use getName()? Can you give an example for your hashCode

@mateusz.fiolka 2013-03-02 13:15:15

@jimmybondy: getName will return a String object which also has a hashCode which can be used

@Antti Kissaniemi 2008-08-26 09:12:42

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

equals() (javadoc) must define an equivalence relation (it must be reflexive, symmetric, 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().

@Antti Kissaniemi 2009-05-28 19:03:29

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.

@aviad 2011-04-12 12:36:29

Special care must be taken of the transient fields.

@K'' 2011-08-12 18:48:18

A great discussion about this question in Effective Java book

@Rok Strniša 2011-11-22 18:58:32

You can get Eclipse to generate the two methods for you: Source > Generate hashCode() and equals().

@zod 2012-07-12 09:10:05

does it matter if we all randomly chose the same prime numbers?

@seinecle 2012-08-11 07:59:09

@QED 2012-08-14 23:23:19

@Darthenius: yours is the most useful!

@bestsss 2013-02-10 14:34:44

make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection This is exactly why overriding equals and hashcode together may not be necessary. Having hashCode pretty much precludes any changes to the object state while equals can tolerate fully mutable objects. You can safely put a mutable object into list as long as the equals contract remains intact but it's untrue for hashset/hashtables. Also if you wish a class to be able to server as key in hash structure it has to be designed as such (not just having hashCode)

@supercat 2013-08-04 16:48:05

@bestsss: A general rule which is good to follow is that at any given time when a mutable aspect of an object's state might change, the object should have one well-defined owner. If an object overrides equals so as to depend upon some mutable state, any Dictionary in which it was stored would "own" that aspect of its state. Since any execution context which tried to alter that state would have to own it, that would imply that the object must be removed from the Dictionary first. Otherwise, if one wants to bend this rule, override hashCode to depend only upon immutable properties.

@AndroidGecko 2013-12-08 18:46:59

@izaban 2013-12-13 19:51:01

The first null check is not necessary given the fact that instanceof returns false if its first operand is null (Effective Java again).

@Rui Marques 2014-01-24 13:09:15

@AndroidGecko maybe it did in the past. Eclipse Kepler did not generate code containing getClass().

@Brian 2014-02-10 20:01:17

Android Studio can also generate equals() and hashCode() for you.

@Mike Housky 2014-03-18 04:52:52

The mathematical term is "equivalence relation", not "equality relation".

@yalkris 2014-07-28 21:06:12

equals is used to add/remove elements from collections like CopyOnWriteArraySet, HashSet if hashCode is equal for two different objects, etc. equals need to be symmetric i.e. if B.equals(C) returns true then C.equals(B) should return the same result. Otherwise your add/remove on those XXXSets behave in a confusing manner. stackoverflow.com/questions/24920563/…

@Amit Parashar 2015-05-28 09:34:59

You are re-calculating hashcode every time hashCode() is called. If the object is immutable, cache the calculated hashcode in the instance. Refer the hashCode impl in String class.

@AbrahamDaniel 2015-06-03 03:31:10

when using "instanceof" instead of "getClass()" symmetry would not always be maintained

@Steiny 2015-06-29 02:37:02

This answer is only half of the story. It fails to mention any of the pitfalls when overriding the equals method in a subclass. It is actually misleading in that simply adding appendSuper in a derived class will solve the problem. It will almost certainly break either symmetry or transitivity.

@Manish Nagar 2016-02-02 06:30:32

@AnttiSykäri you can also add some example like- when we want to insert user defined object into SET that time we need to implement hashCode and equals method so it will add only unique object into SET

@Asif Mushtaq 2016-03-25 18:25:57

@nullpointer 2016-10-13 10:49:25

surprised by the fact that enum is not a part of the answer, shall we not be concerned over such fields?

@David Lavender 2017-12-05 16:32:08

"Use the same set of fields that you use to compute equals() to compute hashCode()" I was taught that hashcode was the "quick look-up", just to narrow the scope of what then needs a full "equals" check. So, in most situations, I would just pick one field (e.g. "age" in this example) rather than always including all the fields. Is that bad practice?

@Ran Biron 2008-08-28 13:16:01

A clarification about the obj.getClass() != getClass().

This statement is the result of equals() being inheritance unfriendly. The JLS (Java language specification) specifies that if A.equals(B) == true then B.equals(A) must also return true. If you omit that statement inheriting classes that override equals() (and change its behavior) will break this specification.

Consider the following example of what happens when the statement is omitted:

Where, if a is not a reference of B, then it might be a be a reference of class A (because you extend it), in this case you call super.equals()too.

@pihentagy 2010-02-25 10:40:10

You can make equals symmetric this way (if comparing a superclass object with subclass object, always use the equals of the subclass) if (obj.getClass() != this.getClass() && obj.getClass().isInstance(this)) return obj.equals(this);

@Ran Biron 2010-12-06 19:16:48

@pihentagy - then I'd get a stackoverflow when the implementation class doesn't override the equals method. not fun.

@Jacob Raihle 2013-08-04 12:32:58

You won't get a stackoverflow. If the equals method is not overridden, you will call the same code again, but the condition for recursion will always be false!

@supercat 2013-12-28 19:41:57

@pihentagy: How does that behave if there are two different derived classes? If a ThingWithOptionSetA can be equal to a Thing provided that all the extra options have default values, and likewise for a ThingWithOptionSetB, then it should be possible for a ThingWithOptionSetA to be compare equal to a ThingWithOptionSetB only if all non-base properties of both objects match their defaults, but I don't see how you test for that.

@nickgrim 2015-06-25 10:24:37

The problem with this it that it breaks transitivity. If you add B b2 = new B(1,99), then b.equals(a) == true and a.equals(b2) == true but b.equals(b2) == false.

@Luna Kong 2013-12-20 06:14:09

There are two methods in super class as java.lang.Object. We need to override them to custom object.

public boolean equals(Object obj)
public int hashCode()

Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.

@rohan kamat 2013-10-24 10:56:39

equals() method is used to determine the equality of two objects.

as int value of 10 is always equal to 10. But this equals() method is about equality of two objects. When we say object, it will have properties. To decide about equality those properties are considered. It is not necessary that all properties must be taken into account to determine the equality and with respect to the class definition and context it can be decided. Then the equals() method can be overridden.

we should always override hashCode() method whenever we override equals() method. If not, what will happen? If we use hashtables in our application, it will not behave as expected. As the hashCode is used in determining the equality of values stored, it will not return the right corresponding value for a key.

Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it.

@Kevin Wong 2008-09-11 03:06:45

In his book Effective Java Programming Language Guide (Addison-Wesley, 2001), Joshua Bloch claims that "There is simply no way to extend an instantiable class and add an aspect while preserving the equals contract." Tal disagrees.

His solution is to implement equals() by calling another nonsymmetric blindlyEquals() both ways. blindlyEquals() is overridden by subclasses, equals() is inherited, and never overridden.

@Blaisorblade 2011-12-14 01:43:12

Have a look at the canEqual method explained here - the same principle makes both solutions work, but with canEqual you don't compare the same fields twice (above, p.x == this.x will be tested in both directions): artima.com/lejava/articles/equality.html

@Kevin 2014-08-12 00:54:28

Point.equals() should have o being cast to a Point (it's trying to call blindlyEquals() on an object). Though that may have been intentional (in an attempt to emphasize the method).

@Kevin 2014-08-12 01:05:55

In any case, I don't think this is a good idea. It makes the Equals contract unnecessarily confusing - someone who takes two Point parameters, a and b, has to be conscious of the possibility that a.getX() == b.getX() and a.getY() == b.getY() can be true, but a.equals(b) and b.equals(a) both be false (if only one is a ColorPoint).

@Aleksandr Dubinsky 2016-02-19 16:37:09

Basically, this is like if (this.getClass() != o.getClass()) return false, but flexible in that it only returns false if the derived class(es) bother to modify equals. Is that right?

@Johannes Schaub - litb 2009-02-27 22:05:04

For equals, look into Secrets of Equals by Angelika Langer. I love it very much. She's also a great FAQ about Generics in Java. View her other articles here (scroll down to "Core Java"), where she also goes on with Part-2 and "mixed type comparison". Have fun reading them!

@Darren Greaves 2008-09-02 21:06:47

One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).
These sorts of things are fairly common when doing Hibernate mappings for example.

If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.
The simplest solution is to not include the getChildren collection in the methods.

@Raedwald 2011-09-29 09:28:37

I think the underlying theory here is to distinguish between the attributes, aggregates and associatinos of an object. The asssociations should not participate in equals(). If a mad scientist created a duplicate of me we would be equivalent. But we would not have the same father.

@erickson 2008-08-28 18:25:36

There are a couple of ways to do your check for class equality before checking member equality, and I think both are useful in the right circumstances.

Use the instanceof operator.

Use this.getClass().equals(that.getClass()).

I use #1 in a final equals implementation, or when implementing an interface that prescribes an algorithm for equals (like the java.util collection interfaces—the right way to check with with (obj instanceof Set) or whatever interface you're implementing). It's generally a bad choice when equals can be overridden because that breaks the symmetry property.

Option #2 allows the class to be safely extended without overriding equals or breaking symmetry.

If your class is also Comparable, the equals and compareTo methods should be consistent too. Here's a template for the equals method in a Comparable class:

@Paul Cantrell 2013-04-24 21:48:24

+1 for this. Neither getClass() nor instanceof is a panacea, and this is a good explanation of how to approach both. Don't think there's any reason not to do this.getClass() == that.getClass() instead of using equals().

@Steiny 2015-06-29 02:27:44

There is one problem with this. Anonymous classes which do not add any aspects nor override the equals method will fail the getClass check even though they should be equal.

@erickson 2015-06-29 23:45:59

@Steiny It's not clear to me that objects of different types should be equal; I'm thinking of different implementations of an interface as a common anonymous class. Can you give an example to support your premise?

@Steiny 2015-07-07 02:53:48

MyClass a = new MyClass(123); MyClass b = new MyClass(123) { // Override some method }; // a.equals(b) is false when using this.getClass().equals(that.getClass())

@erickson 2015-07-07 15:41:17

@Steiny Right. As it should in most cases, especially if a method is overridden instead of added. Consider my example above. If it weren't final, and the compareTo() method were overridden to reverse the sort order, instances of the subclass and superclass should not be considered equal. When these objects were used together in a tree, keys that were "equal" according to an instanceof implementation might not be findable.