-7

While the contract for compareTo method specifies only the sign of return value, why almost the all method implementations return only -1, 0, 1?

Dumas45
  • 501
  • 1
  • 10
  • 20
  • 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
  • 2
    Read 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 Answers3

2

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

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 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
0

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)

Xabster
  • 3,710
  • 15
  • 21
0

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.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115