2

Test code (just to comply SSCCE, obviously there's much better ways to rock your own case-insensitive data models)

public class TestClass implements java.lang.Comparable<TestClass> {

    public String test;

    @Override
    public int compareTo(TestClass o) {
        if (o == null) {
            throw new NullPointerException();
        }
        return equals(o) ? 0 : test.toLowerCase().compareTo(o.test.toLowerCase());
    }

    @Override
    public boolean equals(Object o) {
        return (o == this) ? true : o instanceof TestClass ? test.equalsIgnoreCase(((TestClass) o).test) : false;
    }

    @Override
    public int hashCode() {
        return test.toLowerCase().hashCode();
    }
}

Say, I want my class implementing Comparable to follow the 'strong recommendation' suggested in the API:

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)).

Would it be OK then to use equals() inside compareTo()? Of course we are ensuring that equals() will not be calling compareTo() in return.

Similar: When to include what?

Community
  • 1
  • 1
h.j.k.
  • 1,357
  • 2
  • 20
  • 30
  • I'm asking about the use of equals() in compareTo(), not to discuss when to use equals() or compareTo(). ;) I'm also not delving into the implementation of equals() and and compareTo() in the String class, that is out-of-scope here. The test code is really just to visualize how equals() may be used inside compareTo(). – h.j.k. Sep 06 '13 at 11:57
  • It’s ok but by the way: do not write things like `a? true: b? c: false`. That’s an obfuscated expression for `a || b && c`. I.e `return o==this || o instanceof TestClass && test.equalsIgnoreCase(((TestClass) o).test)` will do the same. – Holger Sep 06 '13 at 12:10
  • Thanks for spotting that! :) I knew something was fishy when I was typing out true/false... Great catch here. – h.j.k. Sep 06 '13 at 13:20

1 Answers1

2

Should be ok as long as you are doing a NPE check before calling equals() inside compareTo().

One more point would be before doing

test.toLowerCase().compareTo(o.test.toLowerCase());

you must also check if test is NULL because "someString".compareTo((String)null) will throws a NullPointerException.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289