While the contract for compareTo method specifies only the sign of return value, why almost the all method implementations return only -1, 0, 1?
-
Can you please elaborate your question more? – madteapot Aug 06 '14 at 10:40
-
What else you suggest ? a,b,c ?? – Suresh Atta Aug 06 '14 at 10:40
-
2Read the documentation. http://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html – Jeroen Vannevel Aug 06 '14 at 10:40
-
please make your question clear !!! – sayan Aug 06 '14 at 10:41
-
Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the [How to Ask](http://stackoverflow.com/help/how-to-ask) page for help clarifying this question. ow us what you have tried, the relevant code and the **specific** issues you are having. We're not here to write it for you. Read up on [how to write a Short, Self Contained, Correct Example (](http://sscce.org/). Then [edit](http://stackoverflow.com/posts/25158221/edit) your question. – RossC Aug 06 '14 at 10:42
3 Answers
... why do almost the all method implementations return only -1, 0, 1?
I can't speak for other programmers, but I typically do this because it is simpler and more convenient to do that in most case. And most important, it is correct.
I imagine that you are thinking along the lines of doing this:
public int compareTo (MyClass other) {
return this.intField - other.intField;
}
Beware. This code is subtly wrong. See this Q&A: Java Integer compareTo() - why use comparison vs. subtraction?
-
Thank you for your reply! I think you are very smart, because the others don't understand my clear question ;) They gave me a lot of minuses – Dumas45 Aug 06 '14 at 12:39
If you have the read the contract, you have read why.
I'll link it anyway: http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html#compareTo(T)

- 3,710
- 15
- 21
When you compare two values, say a
and b
. There are only 3 possibility.
a
equals to b
a
less than b
a
greater than b
So then you use compateTo()
you need to check above cases only. Then 0
means there are equals. -1
mean a
less than b
and 1
means a
greater than b
If a
and b
are objects then reference value consider.

- 34,993
- 17
- 75
- 115
-
@DividebyZero same way. Then reference value come in to play for Objects. are you downvote this? – Ruchira Gayan Ranaweera Aug 06 '14 at 10:44
-
no, i am not the downvoter, i love my reputation and not interested in loosing one by downvoting any answer(questions are exception though :p)... – nobalG Aug 06 '14 at 10:45
-