Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 6 equivalent of Integer.compare

Tags:

java

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?

like image 405
Joren Avatar asked Nov 17 '13 19:11

Joren


People also ask

Can you use == to compare ints in Java?

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

Can compareTo be used for Integers in Java?

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 Integers equal in Java?

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.

How do you compare Integers with 0?

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.


1 Answers

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);
}
like image 64
Alexis C. Avatar answered Oct 13 '22 09:10

Alexis C.