Search code examples
javaintegercompare

Possible values of Integer.compare


In the documentation for Integer.compare(a,b) it says, that it will return a value below 0, if a is smaller than b, and a value above 0 if a is bigger than b.

After I have implemented the method in my code, I have only ever seen it return -1, 0 or 1. My question now is, can it return other values as well, for example -5?

I have to write code where I override the compareTo method, and it has to only return -1, 0, or 1, no other values. In my compareTo I use Integer.compare, so I am wondering if there will be any cases where it will return values outside of -1, 0, 1.


Solution

  • After I have implemented the method in my code, I have only ever seen it return -1, 0 or 1. My question now is, can it return other values as well, for example -5?

    Yes, it can. The current implementation may only return the values you observed, but there is nothing to stop the implementation changing in the future.

    I have to write code where I override the compareTo method, and it has to only return -1, 0, or 1, no other values. In my compareTo I use Integer.compare, so I am wondering if there will be any cases where it will return values outside of -1, 0, 1.

    With the result of Comparable.compareTo (or Comparator.compare, or similar method), you should only ever check the result in relation to zero, that is: == 0, < 0 or > 0 (or !=, <= or >=).