compareTo and deriving

Stephen Colebourne scolebourne at
Tue Dec 5 17:08:28 UTC 2017

On 5 December 2017 at 16:29, Guy Steele <guy.steele at> wrote:
> If the automatically generated `equals` method examines all fields but the `compareTo` method does not, then there can be cases where `compareTo` says that two objects are equal but `equals` says they are

>     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. . . .
>     It is strongly recommended (though not required) that natural orderings be consistent with equals. . . .
>     Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals.

I encoded the same rule in my list that VALJO classes (which are not
unlike records) should obey:
So yes, compareTo should be consistent with equals.

>> On Dec 5, 2017, at 10:17 AM, Brian Goetz <brian.goetz at> wrote:
>> You can look at the "but I have to write compareTo" issue as glass 90% full or 10% empty; a record starts life with a sensible ctor, dtor, accessors, equals, hashCode, and toString.  So adding compareTo is pretty easy.  Note also that there's no way we can reasonably derive compareTo from the state description, since (a) not all state fields are going to be relevant for ordering comparison and (b) the order in which they are declared may not be the natural comparison order.  So somewhere in the program the user is going to have to write down that "a Person is compared by (lastName, firstName)", somehow.

equals() can also have an ordering, where some tests are faster to
perform than others. So, it isn't just compareTo(). If you are going
to allow people to replace the generated equals() with a hand-written
one, then you'd also allow the same for compareTo(). In which case,
you might as well generate the default compareTo() if the user
implements Comparable (using the standard order of fields). If the
order is wrong, they can replace the method with a hand-written one.
In other words, I don't think that (a) or (b) are enough of a problem
to not do the simple implementation (assuming hand-written
replacements are possible).


More information about the amber-spec-observers mailing list