Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top