Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compareTo with primitives -> Integer / int

Is it better to write

int primitive1 = 3, primitive2 = 4; Integer a = new Integer(primitive1); Integer b = new Integer(primitive2); int compare = a.compareTo(b); 

or

int primitive1 = 3, primitive2 = 4; int compare = (primitive1 > primitive2) ? 1 : 0; if(compare == 0){     compare = (primitive1 == primitive2) ? 0 : -1; } 

I think the second one is better, should be faster and more memory optimized. But aren't they equal?

like image 294
Marek Sebera Avatar asked Feb 05 '12 15:02

Marek Sebera


People also ask

Can you use compareTo with integers?

Java Integer compareTo() methodThis method compares two integer objects numerically. 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.

How do you compare primitive integers?

To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).

Does compareTo work with numbers?

compareTo sorts numbers numerically. This is what you want. String. compareTo sorts strings lexicographically; that is, in alphabetical order.

Can we compare integer and int in Java?

In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.


2 Answers

For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.


I would do either

int cmp = a > b ? +1 : a < b ? -1 : 0; 

or a longer version

int cmp; if (a > b)    cmp = +1; else if (a < b)    cmp = -1; else    cmp = 0; 

or

int cmp = Integer.compare(a, b); // in Java 7 int cmp = Double.compare(a, b); // before Java 7 

It's best not to create an object if you don't need to.

Performance wise, the first is best.

If you know for sure that you won't get an overflow you can use

int cmp = a - b; // if you know there wont be an overflow. 

you won't get faster than this.

like image 144
Peter Lawrey Avatar answered Oct 18 '22 10:10

Peter Lawrey


Use Integer.compare(int, int). And don'try to micro-optimize your code unless you can prove that you have a performance issue.

like image 39
MForster Avatar answered Oct 18 '22 10:10

MForster