Official definition
From the reference documents Comparable.compareTo (T) :
Compares this object with the specified object for the order. Returns a negative integer, zero, or a positive integer because this object is less than, equal to, or greater than the specified object.
The developer must provide sgn (x.compareTo (y)) == -sgn (y.compareTo (x)) for all x and y. (This means that x.compareTo (y) should throw an exception; iff y.compareTo (x) throws an exception.)
The developer must also ensure that the relation is transitive: (x.compareTo (y)> 0 & y.compareTo (z)> 0) implies x.compareTo (z)> 0.
Finally, the developer must ensure that x.compareTo (y) == 0 means that sgn (x.compareTo (z)) == sgn (y.compareTo (z)), for all z.
It is highly recommended, but not strictly required, that (x.compareTo (y) == 0) == (x.equals (y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. Recommended language: "Note: this class has a natural order that is incompatible with peers."
In the above description, the notation sgn (expression) denotes the mathematical function signum, which is defined to return one of -1, 0, or 1, depending on whether the value of the expression is negative, zero, or positive.
My version
In short:
this.compareTo(that)
returns
- negative int if this <what
- 0 if it == that
- positive int if it> what
where the implementation of this method determines the actual semantics of < > and == (I do not mean == in the sense of the identification operator of a Java object)
Examples
"abc".compareTo("def")
will give something less than 0, since abc is in alphabetical order before def .
Integer.valueOf(2).compareTo(Integer.valueOf(1))
will give something more than 0 because 2 is greater than 1.
Some additional points
Note. . Good practice for a class implementing Comparable to declare semantics of the compareTo () method in javadocs.
Note: at least one of the following values should be read:
Warning: you should never rely on the return values of compareTo -1 , 0 and 1 . You should always test x < 0 , x == 0 , x > 0 respectively.