views:

391

answers:

5

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;
+18  A: 

It has to do with Integer overflow errors. When thisVal is very large and anotherVal is negative then subtracting will yield a result that is bigger than thisVal which may overflow to be negative.

Itay
+2  A: 

Perhaps it's to avoid overflow / underflow.

Adamski
+17  A: 
polygenelubricants
It's not really broken at all. If you know anything about the numbers you're comparing, you'll probably know that they're safe to compare. Even not knowing, just `((long)a - b)` ought to work. Though you're right; it's very rarely useful.
Vuntic
+1  A: 

Simply speaking, the int type is not big enough to store the difference between two arbitrary int values. For example, the difference between 1.5 billion and -1.5 billion is 3.0 billion, but int cannot hold values greater than 2.1 billion.

FredOverflow
A: 

In addition to the overflow thing, you should note that the version with substraction does not give the same results.

  • The first compareTo version returns one of three possible values: -1, 0, or 1.
  • If you replace the last line with substraction, the result can be any integer value.

If you know there will be no overflow, you could use something like this:

public int compareTo(Integer anotherInteger) {
    return sign(this.value - anotherInteger.valuel);
}
PauliL
You are correct that the results are not the same. But they are not required to be! `compareTo` is only required to return a negative value, zero or a positive value, depending on the sort order of `this` and the other object. See http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Comparable.html#compareTo%28T%29
Christian Semrau