Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Integer compareTo() - why use comparison vs. subtraction?

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; 
like image 760
Vladimir Avatar asked Apr 28 '10 10:04

Vladimir


People also ask

How does compareTo work in Java with integers?

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 is the difference between compareTo and compare?

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.

What does compare () does for Java?

The compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y)


1 Answers

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.

like image 194
Itay Maman Avatar answered Sep 20 '22 13:09

Itay Maman