Page 146:
book wrote:A natural ordering that uses compareTo() is said to be consistent with equals if, and only if, x.equals(y) is true whenever x.compareTo(y) equals 0.
The API doc of Comparable says
API doc wrote: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.
That's different. According to the book's rule, a class which equals() method always returns true, is always consistent, even if its compareTo() method does not return 0. According to the API, equals() must return false if compareTo() doesn't return 0 (and true if it does).
Then follows this:
You might be sorting Product objects by name, but names are not unique. Therefore, the return value of compareTo() might not be 0 when comparing two equal Product objects,
so this compareTo() method is not consistent with equals.
(This refers to the case where two Product objects have the same id values, and different name values.)
Its inconsistency does not follow from the rule in the book's quote, but from the API doc's quote.
(It is also inconsistent because of the following case. Say you have two Product objects with different id values, and with equal name values. Then namecompareTo() returns 0, but equals() returns false. This is because of both the book's rule and the API's rule.)
[edit] Reading it over again, I think the only typo in the book's rule is that the phrase
if, and only if has to be in two places. It should be:
A natural ordering that uses compareTo() is said to be consistent with equals if, and only if: x.equals(y) is true
if, and only if x.compareTo(y) equals 0.