H2ONaCl
H2ONaCl

Reputation: 11269

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.

Upvotes: 0

Views: 137

Answers (4)

kundan bora
kundan bora

Reputation: 3889

I want to just tell you that you should have a particular properties or attribute in objects which you will use to compare two objects of same type.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

The documentation for Comparator has this cautionary note:

The ordering imposed by a comparator c on a set of elements S is said to be consistent with equals if and only if c.compare(e1, e2)==0 has the same boolean value as e1.equals(e2) for every e1 and e2 in S.

Caution should be exercised when using a comparator capable of imposing an ordering inconsistent with equals to order a sorted set (or sorted map). Suppose a sorted set (or sorted map) with an explicit comparator c is used with elements (or keys) drawn from a set S. If the ordering imposed by c on S is inconsistent with equals, the sorted set (or sorted map) will behave "strangely." In particular the sorted set (or sorted map) will violate the general contract for set (or map), which is defined in terms of equals.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

It is explained in the JavaDocs:

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 it is not required, i.e. If two classes are equal according to the compareTo(), they don't have to hold equals(). This is fine because you can for instance sort people by age, so two people with the same age are considered equal with regards to Comparator<Person>, but they obviously don't have to be equal.

However in this particular case you might want to add secondary attributes to comparator if ages are equal (so sorting is always stable and predictable across same-aged people) so after all including the same attributes in compareTo() might be a good idea in some cases.

Upvotes: 0

Corbin
Corbin

Reputation: 33437

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.

Upvotes: 3

Related Questions