Search code examples
javaoverridingcompareto

What are the implications for overriding compareTo?


I am aware that if one overrides equals, hashCode should also be overridden. Are there any similar rules that would apply to overriding compareTo?

This is a Java question.


Solution

  • The expectations of it can be read here: http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

    The part that will be of the most interest to you is probably:

    It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.