In the book OCP Oracle Certified Professional Java SE 8 Programmer II Study Guide it says on page 144 that there are three rules to know when you write your own Comparable#compareTo() method.
The number zero is returned when the current object is equal to the argument to compareTo().
A number less than zero is returned when the current object is smaller than the argument to compareTo().
A number greater than zero is returned when the current object is larger than the arguments to compareTo().
Then it gives an example
And then is says
Lines 3 through 5 implement the compareTo() method. Since an int is a primitive, we can't call a method on it. We could create the Integer wrapper class and call compareTo() on that. It's not necessary, though, since it is so easy to implement compareTo() correctly on our own.
Lines 11 through 13 confirm that we've implemented compareTo() correctly. Line 11 compares a smaller id to a larger one, and therefore it prints a negative number. Line 12 compares animals with the same id, and therefore it prints 0. Line 13 compares a larger id to a smaller one, and therefore it returns a positive number.
There's a bug in this code. When you change line 9 to a1.id = Integer.MIN_VALUE; the output becomes 2147483641, 0 and -2147483641. Line 11 still compares a smaller id to a larger one, but it prints a positive number. And line 13 still compares a larger id to a smaller one, but it returns a negative number.
A better solution would be to "create the Integer wrapper class and call compareTo() on that" or call the method Integer#compare(int x, int y). Both solutions return -1, 0 and 1 (when I run it on OpenJDK Runtime Environment 8).
Since some time now I am using below style, not because it is less verbose (on the contrary!), but I like working with Comparators, given their flexibility:
posted 1 month ago
Agree that Comparators give you more flexibility, but why are you making Animal implement Comparable? (I presume you are simply showing how to implement Comparable?) Comparable “imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering . . . ” I am not convinced that Animals have a natural ordering; you can order them by id, size, age, etc., in which case a Comparator would be better. Things like numbers and dates have a natural ordering. and so do Strings, viz. Asciibetical. That is why the API provides this Comparator, which makes me think that Strings don't actually have a natural ordering after all
posted 1 month ago
I just used OP's example. In this case, as both OP and you state, a simple Integer.compare would do the trick much easier. But I just wanted to show the way I did it, comes in handy when preparing for the OCPJP.