In Java 7 I can use Integer.compare
, but when I try to use it in Java 6 it gives me the error:
cannot find symbol
symbol : method compare(int,int)
location: class java.lang.Integer
How do I create a similar function in Java 6?
Method 1: Compare two Integers in Java Using Comparison Operator. The most commonly used method by programmers to compare two integers is the Comparison operator “==”. It gives “1” if the specified variables are equal; else, it returns “0”.
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.
To check two numbers for equality in Java, we can use the Equals() method as well as the == operator. Firstly, let us set Integers. Integer val1 = new Integer(5); Integer val2 = new Integer(5); Now, to check whether they are equal or not, let us use the == operator.
Java Integer compareTo() method It returns the result of the value 0 if Integer is equal to the argument Integer, a value less than 0 if Integer is less than the argument Integer and a value greater than 0 if Integer is greater than the argument Integer. This method is specified by Comparable<Integer>Interface.
This is specified in the doc :
Compares two int values numerically. The value returned is identical to what would be returned by:
Integer.valueOf(x).compareTo(Integer.valueOf(y))
So you can use :
Integer.valueOf(x).compareTo(Integer.valueOf(y))
How do create a similar function in Java 6?
The source is open and you can find the implementation here.
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With