What is the difference between returning 0
, returning 1
and returning -1
in compareTo()
in Java?
They just say that there are three distinct return values: a negative int, zero, and a positive int. One of them means this < that, one means this > that and one means this == that.
The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0. It compares strings on the basis of the Unicode value of each character in the strings.
If the first string is less than the second string lexicographically, it returns a negative number, and if the first string is lexicographically equal to the second string, it returns 0. Note: if string1 > string2, it returns positive number. if string1 < string2, it returns negative number.
From the reference docs of Comparable.compareTo(T):
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)
The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.
Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.
It is strongly 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. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."
In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.
In short:
this.compareTo(that)
returns
where the implementation of this method determines the actual semantics of <
>
and ==
(I don't mean ==
in the sense of java's object identity operator)
"abc".compareTo("def")
will yield something smaller than 0 as abc
is alphabetically before def
.
Integer.valueOf(2).compareTo(Integer.valueOf(1))
will yield something larger than 0 because 2 is larger than 1.
Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.
Note: you should read at least one of the following:
Warning: you should never rely on the return values of compareTo being -1
, 0
and 1
. You should always test for x < 0
, x == 0
, x > 0
, respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With