title: Implementing equals method using compareTo
body: <p>General question: When implementing an override of the default <code>equals</code> method in Java, what concerns should I have about simply utilizing an already implemented <code>compareTo</code> method vs writing independent logic into the equals method? I noticed someone mention in another question that <code>foo.equals((String)null)</code> returns false whereas <code>String.compareTo((String)null)</code> throws a <code>NullPointerException</code>. What makes these inconsistent results ideal functionality?</p>
  
  <p>Sample <code>equals</code> method:</p>
  
  <pre><code>@Override
  public boolean equals(Object obj) {
      if (obj != null &amp;&amp; obj instanceof MyClass) {
          MyClass msg = (MyClass)obj;
          return this.compareTo(msg) == 0;
      }
      return false;
  }
  </code></pre>
  
  <p><strong>Edit:</strong>
  Quote from documentation on <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html" rel="noreferrer">Comparable</a></p>
  
  <blockquote>
    <p>The natural ordering for a class C is said to be consistent with
    equals if and only if e1.compareTo(e2) == 0 has the same boolean value
    as e1.equals(e2) for every e1 and e2 of class C. Note that null is not
    an instance of any class, and e.compareTo(null) should throw a
    NullPointerException even though e.equals(null) returns false</p>
  </blockquote>
  
  <p><strong>Edit:</strong></p>
  
  <p>After further review, I find it of note that the <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html" rel="noreferrer">Comparable</a> documentation also states the following:</p>
  
  <blockquote>
    <p>The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)</p>
  </blockquote>
  
  <p>Ergo, since <code>null.compareTo(x)</code> obviously throws a <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/NullPointerException.html" rel="noreferrer">NPE</a>, <code>x.compareTo(null)</code> should throw a NPE as well. Whereas for equals, that is not necessarily the case. I am pretty big on the proper handling of NPEs, so I find this relatively significant.</p>