I've found that java.lang.Integer
implementation of compareTo
method looks as follows:
public int compareTo(Integer anotherInteger) { int thisVal = this.value; int anotherVal = anotherInteger.value; return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1)); }
The question is why use comparison instead of subtraction:
return thisVal - anotherVal;
compareTo() method compares two Integer objects numerically. This method returns the value 0 if this Integer is equal to the argument Integer, a value less than 0 if this Integer is numerically less than the argument Integer and a value greater than 0 if this Integer is numerically greater than the argument Integer.
What are the differences between compareTo() and compare() methods in Java? The Comparable interface provides a compareTo() method for the ordering of objects. This ordering is called the class's natural ordering and the compareTo() method is called its natural comparison method.
The compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y)
This is due to integer overflow. When thisVal
is very large and anotherVal
is negative then subtracting the latter from the former yields a result that is bigger than thisVal
which may overflow to the negative range.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With