<p>What issues / pitfalls must be considered when overriding <code>equals</code> and <code>hashCode</code>?</p>

[{'answer_id': 27609, 'author': 'Antti Kissaniemi', 'author_id': 2948, 'author_profile': 'https://Stackoverflow.com/users/2948', 'pm_score': 12, 'selected': True, 'text': '<h3>The theory (for the language lawyers and the mathematically inclined):</h3>\n\n<p><code>equals()</code> (<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)" rel="noreferrer">javadoc</a>) must define an equivalence relation (it must be <em>reflexive</em>, <em>symmetric</em>, and <em>transitive</em>). In addition, it must be <em>consistent</em> (if the objects are not modified, then it must keep returning the same value). Furthermore, <code>o.equals(null)</code> must always return false.</p>\n\n<p><code>hashCode()</code> (<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()" rel="noreferrer">javadoc</a>) must also be <em>consistent</em> (if the object is not modified in terms of <code>equals()</code>, it must keep returning the same value).</p>\n\n<p>The <strong>relation</strong> between the two methods is:</p>\n\n<blockquote>\n  <p><em>Whenever <code>a.equals(b)</code>, then <code>a.hashCode()</code> must be same as <code>b.hashCode()</code>.</em></p>\n</blockquote>\n\n<h3>In practice:</h3>\n\n<p>If you override one, then you should override the other.</p>\n\n<p>Use the same set of fields that you use to compute <code>equals()</code> to compute <code>hashCode()</code>.</p>\n\n<p>Use the excellent helper classes <a href="http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html" rel="noreferrer">EqualsBuilder</a> and <a href="http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html" rel="noreferrer">HashCodeBuilder</a> from the <a href="http://commons.apache.org/lang/" rel="noreferrer">Apache Commons Lang</a> library. An example:</p>\n\n<pre><code>public class Person {\n    private String name;\n    private int age;\n    // ...\n\n    @Override\n    public int hashCode() {\n        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers\n            // if deriving: appendSuper(super.hashCode()).\n            append(name).\n            append(age).\n            toHashCode();\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n       if (!(obj instanceof Person))\n            return false;\n        if (obj == this)\n            return true;\n\n        Person rhs = (Person) obj;\n        return new EqualsBuilder().\n            // if deriving: appendSuper(super.equals(obj)).\n            append(name, rhs.name).\n            append(age, rhs.age).\n            isEquals();\n    }\n}\n</code></pre>\n\n<h3>Also remember:</h3>\n\n<p>When using a hash-based <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html" rel="noreferrer">Collection</a> or <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Map.html" rel="noreferrer">Map</a> such as <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashSet.html" rel="noreferrer">HashSet</a>, <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashSet.html" rel="noreferrer">LinkedHashSet</a>, <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html" rel="noreferrer">HashMap</a>, <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html" rel="noreferrer">Hashtable</a>, or <a href="http://download.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html" rel="noreferrer">WeakHashMap</a>, 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, <a href="http://www.javapractices.com/topic/TopicAction.do?Id=29" rel="noreferrer">which has also other benefits</a>.</p>\n'}, {'answer_id': 32223, 'author': 'Ran Biron', 'author_id': 931, 'author_profile': 'https://Stackoverflow.com/users/931', 'pm_score': 6, 'selected': False, 'text': '<p>A clarification about the <code>obj.getClass() != getClass()</code>.</p>\n\n<p>This statement is the result of <code>equals()</code> being inheritance unfriendly. The JLS (Java language specification) specifies that if <code>A.equals(B) == true</code> then <code>B.equals(A)</code> must also return <code>true</code>. If you omit that statement inheriting classes that override <code>equals()</code> (and change its behavior) will break this specification.</p>\n\n<p>Consider the following example of what happens when the statement is omitted:</p>\n\n<pre><code>    class A {\n      int field1;\n\n      A(int field1) {\n        this.field1 = field1;\n      }\n\n      public boolean equals(Object other) {\n        return (other != null &amp;&amp; other instanceof A &amp;&amp; ((A) other).field1 == field1);\n      }\n    }\n\n    class B extends A {\n        int field2;\n\n        B(int field1, int field2) {\n            super(field1);\n            this.field2 = field2;\n        }\n\n        public boolean equals(Object other) {\n            return (other != null &amp;&amp; other instanceof B &amp;&amp; ((B)other).field2 == field2 &amp;&amp; super.equals(other));\n        }\n    }    \n</code></pre>\n\n<p>Doing <code>new A(1).equals(new A(1))</code> Also, <code>new B(1,1).equals(new B(1,1))</code> result give out true, as it should.</p>\n\n<p>This looks all very good, but look what happens if we try to use both classes:</p>\n\n<pre><code>A a = new A(1);\nB b = new B(1,1);\na.equals(b) == true;\nb.equals(a) == false;\n</code></pre>\n\n<p>Obviously, this is wrong.</p>\n\n<p>If you want to ensure the symmetric condition. a=b if b=a and the Liskov substitution principle call <code>super.equals(other)</code> not only in the case of <code>B</code> instance, but check after for <code>A</code> instance:</p>\n\n<pre><code>if (other instanceof B )\n   return (other != null &amp;&amp; ((B)other).field2 == field2 &amp;&amp; super.equals(other)); \nif (other instanceof A) return super.equals(other); \n   else return false;\n</code></pre>\n\n<p>Which will output:</p>\n\n<pre><code>a.equals(b) == true;\nb.equals(a) == true;\n</code></pre>\n\n<p>Where, if <code>a</code> is not a reference of <code>B</code>, then it might be a be a reference of class <code>A</code> (because you extend it), in this case you call <code>super.equals()</code> <strong>too</strong>.</p>\n'}, {'answer_id': 33010, 'author': 'erickson', 'author_id': 3474, 'author_profile': 'https://Stackoverflow.com/users/3474', 'pm_score': 4, 'selected': False, 'text': "<p>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.</p>\n\n<ol>\n<li>Use the <code>instanceof</code> operator.</li>\n<li>Use <code>this.getClass().equals(that.getClass())</code>.</li>\n</ol>\n\n<p>I use #1 in a <code>final</code> equals implementation, or when implementing an interface that prescribes an algorithm for equals (like the <code>java.util</code> collection interfaces&mdash;the right way to check with with <code>(obj instanceof Set)</code> or whatever interface you're implementing). It's generally a bad choice when equals can be overridden because that breaks the symmetry property.</p>\n\n<p>Option #2 allows the class to be safely extended without overriding equals or breaking symmetry.</p>\n\n<p>If your class is also <code>Comparable</code>, the <code>equals</code> and <code>compareTo</code> methods should be consistent too. Here's a template for the equals method in a <code>Comparable</code> class:</p>\n\n<pre><code>final class MyClass implements Comparable&lt;MyClass&gt;\n{\n\n  …\n\n  @Override\n  public boolean equals(Object obj)\n  {\n    /* If compareTo and equals aren't final, we should check with getClass instead. */\n    if (!(obj instanceof MyClass)) \n      return false;\n    return compareTo((MyClass) obj) == 0;\n  }\n\n}\n</code></pre>\n"}, {'answer_id': 40669, 'author': 'Darren Greaves', 'author_id': 151, 'author_profile': 'https://Stackoverflow.com/users/151', 'pm_score': 3, 'selected': False, 'text': "<p>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).<br>\nThese sorts of things are fairly common when doing Hibernate mappings for example.</p>\n\n<p>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.<br>\nThe simplest solution is to not include the getChildren collection in the methods.</p>\n"}, {'answer_id': 55736, 'author': 'Kevin Wong', 'author_id': 4792, 'author_profile': 'https://Stackoverflow.com/users/4792', 'pm_score': 6, 'selected': False, 'text': '<p>For an inheritance-friendly implementation, check out Tal Cohen\'s solution, <a href="http://www.drdobbs.com/jvm/java-qa-how-do-i-correctly-implement-th/184405053" rel="noreferrer">How Do I Correctly Implement the equals() Method?</a></p>\n\n<p>Summary:</p>\n\n<p>In his book <a href="https://rads.stackoverflow.com/amzn/click/com/0201310058" rel="noreferrer" rel="nofollow noreferrer">Effective Java Programming Language Guide</a> (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.</p>\n\n<p>His solution is to implement equals() by calling another nonsymmetric blindlyEquals() both ways.  blindlyEquals() is overridden by subclasses, equals() is inherited, and never overridden.</p>\n\n<p>Example:</p>\n\n<pre><code>class Point {\n    private int x;\n    private int y;\n    protected boolean blindlyEquals(Object o) {\n        if (!(o instanceof Point))\n            return false;\n        Point p = (Point)o;\n        return (p.x == this.x &amp;&amp; p.y == this.y);\n    }\n    public boolean equals(Object o) {\n        return (this.blindlyEquals(o) &amp;&amp; o.blindlyEquals(this));\n    }\n}\n\nclass ColorPoint extends Point {\n    private Color c;\n    protected boolean blindlyEquals(Object o) {\n        if (!(o instanceof ColorPoint))\n            return false;\n        ColorPoint cp = (ColorPoint)o;\n        return (super.blindlyEquals(cp) &amp;&amp; \n        cp.color == this.color);\n    }\n}\n</code></pre>\n\n<p>Note that equals() must work across inheritance hierarchies if the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noreferrer">Liskov Substitution Principle</a> is to be satisfied.</p>\n'}, {'answer_id': 256447, 'author': 'Johannes Brodwall', 'author_id': 27658, 'author_profile': 'https://Stackoverflow.com/users/27658', 'pm_score': 8, 'selected': False, 'text': '<p>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!</p>\n\n<p><strong>Lazy loaded objects are subclasses</strong></p>\n\n<p>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 that<code>this.getClass() == o.getClass()</code> will return <code>false</code>. For example:</p>\n\n<pre><code>Person saved = new Person("John Doe");\nLong key = dao.save(saved);\ndao.flush();\nPerson retrieved = dao.retrieve(key);\nsaved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy\n</code></pre>\n\n<p><em>If you\'re dealing with an ORM, using <code>o instanceof Person</code> is the only thing that will behave correctly.</em></p>\n\n<p><strong>Lazy loaded objects have null-fields</strong></p>\n\n<p>ORMs usually use the getters to force loading of lazy loaded objects. This means that <code>person.name</code> will be <code>null</code> if <code>person</code> is lazy loaded, even if <code>person.getName()</code> forces loading and returns "John Doe". In my experience, this crops up more often in <code>hashCode()</code> and <code>equals()</code>.</p>\n\n<p><em>If you\'re dealing with an ORM, make sure to always use getters, and never field references in <code>hashCode()</code> and <code>equals()</code>.</em></p>\n\n<p><strong>Saving an object will change its state</strong></p>\n\n<p>Persistent objects often use a <code>id</code> 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 <code>hashCode()</code>. But you can use it in <code>equals()</code>.</p>\n\n<p>A pattern I often use is</p>\n\n<pre><code>if (this.getId() == null) {\n    return this == other;\n}\nelse {\n    return this.getId().equals(other.getId());\n}\n</code></pre>\n\n<p>But: you cannot include <code>getId()</code> in <code>hashCode()</code>. If you do, when an object is persisted, its <code>hashCode</code> changes. If the object is in a <code>HashSet</code>, you\'ll "never" find it again.</p>\n\n<p>In my <code>Person</code> example, I probably would use <code>getName()</code> for <code>hashCode</code> and <code>getId()</code> plus <code>getName()</code> (just for paranoia) for <code>equals()</code>. It\'s okay if there are some risk of "collisions" for <code>hashCode()</code>, but never okay for <code>equals()</code>.</p>\n\n<p><em><code>hashCode()</code> should use the non-changing subset of properties from <code>equals()</code></em></p>\n'}, {'answer_id': 596866, 'author': 'Johannes Schaub - litb', 'author_id': 34509, 'author_profile': 'https://Stackoverflow.com/users/34509', 'pm_score': 4, 'selected': False, 'text': '<p>For equals, look into <strong><a href="http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html" rel="noreferrer">Secrets of Equals</a></strong> by <a href="http://www.angelikalanger.com/" rel="noreferrer">Angelika Langer</a>. I love it very much. She\'s also a great FAQ about <strong><a href="http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html" rel="noreferrer">Generics in Java</a></strong>. View her other articles <a href="http://www.angelikalanger.com/Articles/Topics.html#JAVA" rel="noreferrer">here</a> (scroll down to "Core Java"), where she also goes on with Part-2 and "mixed type comparison". Have fun reading them!</p>\n'}, {'answer_id': 14827378, 'author': 'Eugene', 'author_id': 1059372, 'author_profile': 'https://Stackoverflow.com/users/1059372', 'pm_score': 5, 'selected': False, 'text': '<p>Still amazed that none recommended the guava library for this. </p>\n\n<pre><code> //Sample taken from a current working project of mine just to illustrate the idea\n\n    @Override\n    public int hashCode(){\n        return Objects.hashCode(this.getDate(), this.datePattern);\n    }\n\n    @Override\n    public boolean equals(Object obj){\n        if ( ! obj instanceof DateAndPattern ) {\n            return false;\n        }\n        return Objects.equal(((DateAndPattern)obj).getDate(), this.getDate())\n                &amp;&amp; Objects.equal(((DateAndPattern)obj).getDate(), this.getDatePattern());\n    }\n</code></pre>\n'}, {'answer_id': 15599729, 'author': 'Khaled.K', 'author_id': 2128327, 'author_profile': 'https://Stackoverflow.com/users/2128327', 'pm_score': 3, 'selected': False, 'text': '<p>Logically we have:</p>\n\n<p><code>a.getClass().equals(b.getClass()) &amp;&amp; a.equals(b)</code> ⇒ <code>a.hashCode() == b.hashCode()</code></p>\n\n<p>But <strong>not</strong> vice-versa!</p>\n'}, {'answer_id': 19563996, 'author': 'rohan kamat', 'author_id': 2335562, 'author_profile': 'https://Stackoverflow.com/users/2335562', 'pm_score': 4, 'selected': False, 'text': '<p>equals() method is used to determine the equality of two objects.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>Default implementation given is hashCode() method in Object class uses the internal address of the object and converts it into integer and returns it.</p>\n\n<pre><code>public class Tiger {\n  private String color;\n  private String stripePattern;\n  private int height;\n\n  @Override\n  public boolean equals(Object object) {\n    boolean result = false;\n    if (object == null || object.getClass() != getClass()) {\n      result = false;\n    } else {\n      Tiger tiger = (Tiger) object;\n      if (this.color == tiger.getColor()\n          &amp;&amp; this.stripePattern == tiger.getStripePattern()) {\n        result = true;\n      }\n    }\n    return result;\n  }\n\n  // just omitted null checks\n  @Override\n  public int hashCode() {\n    int hash = 3;\n    hash = 7 * hash + this.color.hashCode();\n    hash = 7 * hash + this.stripePattern.hashCode();\n    return hash;\n  }\n\n  public static void main(String args[]) {\n    Tiger bengalTiger1 = new Tiger("Yellow", "Dense", 3);\n    Tiger bengalTiger2 = new Tiger("Yellow", "Dense", 2);\n    Tiger siberianTiger = new Tiger("White", "Sparse", 4);\n    System.out.println("bengalTiger1 and bengalTiger2: "\n        + bengalTiger1.equals(bengalTiger2));\n    System.out.println("bengalTiger1 and siberianTiger: "\n        + bengalTiger1.equals(siberianTiger));\n\n    System.out.println("bengalTiger1 hashCode: " + bengalTiger1.hashCode());\n    System.out.println("bengalTiger2 hashCode: " + bengalTiger2.hashCode());\n    System.out.println("siberianTiger hashCode: "\n        + siberianTiger.hashCode());\n  }\n\n  public String getColor() {\n    return color;\n  }\n\n  public String getStripePattern() {\n    return stripePattern;\n  }\n\n  public Tiger(String color, String stripePattern, int height) {\n    this.color = color;\n    this.stripePattern = stripePattern;\n    this.height = height;\n\n  }\n}\n</code></pre>\n\n<p>Example Code Output:</p>\n\n<pre><code>bengalTiger1 and bengalTiger2: true \nbengalTiger1 and siberianTiger: false \nbengalTiger1 hashCode: 1398212510 \nbengalTiger2 hashCode: 1398212510 \nsiberianTiger hashCode: –1227465966\n</code></pre>\n'}, {'answer_id': 20697433, 'author': 'Luna Kong', 'author_id': 2038772, 'author_profile': 'https://Stackoverflow.com/users/2038772', 'pm_score': 5, 'selected': False, 'text': '<p>There are two methods in super class as java.lang.Object. We need to override them to custom object.</p>\n\n<pre><code>public boolean equals(Object obj)\npublic int hashCode()\n</code></pre>\n\n<p>Equal objects must produce the same hash code as long as they are equal, however unequal objects need not produce distinct hash codes.</p>\n\n<pre><code>public class Test\n{\n    private int num;\n    private String data;\n    public boolean equals(Object obj)\n    {\n        if(this == obj)\n            return true;\n        if((obj == null) || (obj.getClass() != this.getClass()))\n            return false;\n        // object must be Test at this point\n        Test test = (Test)obj;\n        return num == test.num &amp;&amp;\n        (data == test.data || (data != null &amp;&amp; data.equals(test.data)));\n    }\n\n    public int hashCode()\n    {\n        int hash = 7;\n        hash = 31 * hash + num;\n        hash = 31 * hash + (null == data ? 0 : data.hashCode());\n        return hash;\n    }\n\n    // other methods\n}\n</code></pre>\n\n<p>If you want get more, please check this link as <a href="http://www.javaranch.com/journal/2002/10/equalhash.html" rel="noreferrer">http://www.javaranch.com/journal/2002/10/equalhash.html</a></p>\n\n<p>This is another example,\n<a href="http://java67.blogspot.com/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html" rel="noreferrer">http://java67.blogspot.com/2013/04/example-of-overriding-equals-hashcode-compareTo-java-method.html</a></p>\n\n<p>Have Fun! @.@</p>\n'}]
['https://Stackoverflow.com/questions/27581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/797/']