开发者

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

开发者 https://www.devze.com 2023-03-24 12:26 出处:网络
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.

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. B开发者_运维百科ut 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 ....


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


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.


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!


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号