87

What is the difference between returning 0, returning 1 and returning -1 in compareTo() in Java?

mike
  • 4,929
  • 4
  • 40
  • 80
Magggi
  • 1,145
  • 2
  • 12
  • 17

7 Answers7

102

Official Definition

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.

My Version

In short:

this.compareTo(that)

returns

  • a negative int if this < that
  • 0 if this == that
  • a positive int if this > that

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)

Examples

"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.

Some additional points

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.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • Remember, in the documentation they talk about `sgn()`, not directly -1 and 1. You should add this to your short version. – Colin Hebert Sep 22 '10 at 15:03
  • I know. I prefer real language to mathematical mumbo-jumbo (boy am I glad that you can't downvote comments :-)), so I wrote *-1 (or smaller)* and *1 (or larger)*, respectively. – Sean Patrick Floyd Sep 22 '10 at 15:06
  • 1
    Interestingly, the official docs say **at no point** that a negative int actually means *this < that*. 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*. Which is which, the docs do not specify at any point - in fact, you could say, the authors tried hard to write around that detail and leave it open. – O. R. Mapper Jun 19 '13 at 21:13
  • @O.R.Mapper I disagree. "Returns a negative integer, zero, or a positive integer **as this object is** less than, equal to, or greater than the specified object." The "as this object is" part maps integers to relations. – Sean Patrick Floyd Jun 20 '13 at 06:58
  • @SeanPatrickFloyd: I have always interpreted `compareTo` as you say, but now I'm finding myself in the situation of defending my assumption that things are as you say towards QA people who insist that the Java docs do not explicitly say "a negative integer means less than" etc. and thus any code that assumes so is incorrect. If there are any more explicit statements about that in the Java docs, I'd like to learn about them; I couldn't find any so far. – O. R. Mapper Jun 20 '13 at 07:02
  • @O.R.Mapper "and thus any code that assumes so is incorrect" ROFL! So the following are all incorrect: java.util.Tree(Map|Set), Collections.sort(), Arrays.sort() and many other places. Please! If you have to cope with guys like that then either they or you are in the wrong job. – Sean Patrick Floyd Jun 20 '13 at 08:05
  • In your warning you say "you should never rely on the return values of compareTo..." Why not? In what situations would compareTo yield something other than -1, 0, or 1? – kojow7 Nov 07 '17 at 18:15
  • 1
    @kojow I haven't come across such an implementation, but [the contract clearly says](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-): "Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object." – Sean Patrick Floyd Nov 07 '17 at 23:37
  • @kowjow7 System.out.println("alpha".compareTo("deta")); yields -3 – Aaron Dec 08 '20 at 21:30
55

I use this mnemonic :

a.compareTo(b) < 0 // a < b

a.compareTo(b) > 0 // a > b

a.compareTo(b) == 0 // a == b

You keep the signs and always compare the result of compareTo() to 0

Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
34

Answer in short: (search your situation)

  • 1.compareTo(0) (return: 1)
  • 1.compareTo(1) (return: 0)
  • 0.comapreTo(1) (return: -1)
user1012506
  • 2,048
  • 1
  • 26
  • 45
5

take example if we want to compare "a" and "b", i.e ("a" == this)

  1. negative int if a < b
  2. if a == b
  3. Positive int if a > b
Anthon
  • 69,918
  • 32
  • 186
  • 246
bhavesh
  • 151
  • 1
  • 4
3

It can be used for sorting, and 0 means "equal" while -1, and 1 means "less" and "more (greater)".

Any return value that is less than 0 means that left operand is lesser, and if value is bigger than 0 then left operand is bigger.

Michał Niklas
  • 53,067
  • 18
  • 70
  • 114
  • 2
    It's negative, positive and 0, not simply -1, 1 and 0 – Colin Hebert Sep 22 '10 at 15:02
  • Colin, there was -1, 0 and 1 in question. And yes, while some comparators return only one of those values, other can return any value, where negative means that left operand is smaller, zero means both operands are equal, and positive means left is bigger. Outside the Java land thats like `strcmp()` from C works. – Michał Niklas Sep 23 '10 at 09:25
2
int x = thisObject.compareTo(anotherObject);

The compareTo() method returns an int with the following characteristics:

  • negative If thisObject < anotherObject
  • zero If thisObject == anotherObject
  • positive If thisObject > anotherObject
fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

System.out.println(A.compareTo(B)>0?"Yes":"No")

if the value of A>B it will return "Yes" or "No".