Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I like having as a template a "safer" equals() definition:</p> <pre><code> /** * Implement equals based on ${cursor}. &lt;br /&gt; * See {@link #compareTo(Object) compareTo} * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(final Object anObject) { boolean res = false; if(anObject == null) { return false; } if(anObject == this) { return true; } if(anObject.getClass() == this.getClass()) { res = this.compareTo(anObject) == 0; } return res; } </code></pre> <p>To be sure to always avoid <strong>Eq: equals method overrides equals in superclass and may not be symmetric</strong> (<code>EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC</code>), where:</p> <blockquote> <p>This class defines an equals method that overrides an equals method in a superclass. Both equals methods methods use instanceof in the determination of whether two objects are equal. </p> <p>This is fraught with peril, since it is important that the equals method is symmetrical (in other words, <code>a.equals(b) == b.equals(a)</code>).<br> If <code>B</code> is a subtype of <code>A</code>, and <code>A</code>'s equals method checks that the argument is an <code>instanceof A</code>, and B's equals method checks that the argument is an <code>instanceof B</code>, it is quite likely that the equivalence relation defined by these methods is not symmetric.</p> </blockquote> <hr> <p>This is only for classes implementing <code>Comparable</code> and allows for:</p> <ul> <li>an implementation of equals which is always the same;</li> <li>all comparison logics to be located into one place only (the <code>compareTo()</code> function);</li> <li>the compliance with the javadoc of <code>Comparable#compareTo()</code> asking to ensure that <code>(x.compareTo(y)==0) == (x.equals(y))</code> (strongly recommended, but not strictly required though).</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload