Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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 ....

like image 381
rxin Avatar asked Aug 02 '11 18:08

rxin


People also ask

How do you compare Integer classes in Java?

Java Integer compare() methodpublic static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero.

Can you compare Integer objects in Java?

In Java, for comparing two objects, use the “equals()” method. It outputs the boolean value “true” if both objects are the same; else, it returns “false”. We can also compare two integer objects as a reference by utilizing the “equals()” method.

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.

How do you compare two ints?

compare(int x, int y) compare() compares two int values numerically and returns an integer value. If x>y then the method returns an int value greater than zero. If x=y then the method returns zero. If x<y then the method returns an int value less than zero.


1 Answers

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

like image 146
Preston Avatar answered Oct 02 '22 00:10

Preston