What does compareTo() actually return?

后端 未结 4 1888
感动是毒
感动是毒 2021-01-20 16:53

The compareTo() method in Java returns a value greater/equal/less than 0 and i know that. However, the value itself is my question. What is the difference betwe

4条回答
  •  庸人自扰
    2021-01-20 16:56

    The exact value does not matter - all that the Comparable (as well as Comparator) interface cares about is whether the value is negative, zero or positive.

    This is to make things simple for implementations of the interface. When implementing it, you may choose to return the basic -1, 0 or 1 (this is usual if the comparison relies on evaluating some conditions), or you may use any arbitrary negative or positive value if it suits you better - e.g. you can compare two integers by returning this.i - other.i.


    In your particular given example, my guess would be:

    • -1 is difference in the third letter's code point: 'l' - 'm' == -1
    • -5 is difference in the first letter's code point: 'h' - 'm' == -5

    But the important part is that you shall not rely on it to be that way - it's an implementation detail, and according to Comparable's contract any negative value shall be treated the same ("less than").

提交回复
热议问题