rxin
rxin

Reputation: 1786

How come Java's Integer class does not have compare() method?

Double has Double.compare for comparing two double primitives. Why doesn't Integer have one?

I understand it's some trivial amount of code to write, but asking out of curiosity.

Edit: I realize both Integer and Double have compareTo. But using compareTo requires boxing the int primitive in an Integer object, which has a pretty high cost. Also, inta > intb is not the same as compare(inta, intb), as the latter returns +1, 0, or -1, while the former is true/false ....

Upvotes: 18

Views: 4128

Answers (5)

Michael Berry
Michael Berry

Reputation: 72284

Comparing ints in this way is trivial, comparing doubles is actually much more complicated than it might first seem. You have to deal with things such as error values, and less obviously cases such as NaN.

See this question for details.

Either way, as of Java 7, you'll have such a method for ints as well!

Upvotes: 4

Preston
Preston

Reputation: 3271

It was a oversight that Java 7 will resolve

http://download.oracle.com/javase/7/docs/api/java/lang/Integer.html#compare%28int,%20int%29

public static int compare(int x, int y)

Compares two int values numerically. The value returned is identical to what would be returned by:

Integer.valueOf(x).compareTo(Integer.valueOf(y))

Parameters: x - the first int to compare y - the second int to compare Returns: the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y Since: 1.7

Upvotes: 19

zw324
zw324

Reputation: 27180

The compare in Double has the same effect as:

new Double(d1).compareTo(new Double(d2))

Which means it takes NaN, +0 and -0 into account (quoting the doc for compareTo()):

  • Double.NaN is considered by this method to be equal to itself and greater than all other double values (including Double.POSITIVE_INFINITY).
  • 0.0d is considered by this method to be greater than -0.0d.

Since Integer does not have NaN, and both +0 and -0 will be regarded as just 0, such a method is not really needed for functionality.

Upvotes: 6

Roland Illig
Roland Illig

Reputation: 41625

It's probably because the compare operation is relatively simple (but still many people get it wrong). And compared to double, it really is.

I too would like to have this method built-in, which makes other people write simpler code. But as long as Oracle doesn't see it as a problem, we have to rely on Google's Guava or similar libraries to provide the missing bits.

Upvotes: 0

Paul Sonier
Paul Sonier

Reputation: 39480

Floating point values cannot necessarily be binarily compared, because of imprecision in the floating point representation, therefore, a compare() operator is required to compare two floating point values, essentially making sure that the difference between them is not greater than a (small) error value. Integers can be binarily compared, so can use the equality operator.

Upvotes: 2

Related Questions