可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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.
回答2:
Use Integer.compare(int, int)
. And don'try to micro-optimize your code unless you can prove that you have a performance issue.
回答3:
May I propose a third
((Integer) a).compareTo(b)
回答4:
Wrapping int primitive into Integer object will cost you some memory, but the difference will be only significant in very rare(memory demand) cases (array with 1000+ elements). I will not recommend using new Integer(int a) constructor this way. This will suffice :
Integer a = 3;
About comparision there is Math.signum(double d).
compare= (int) Math.signum(a-b);
回答5:
They're already ints. Why not just use subtraction?
compare = a - b;
Note that Integer.compareTo() doesn't necessarily return only -1, 0 or 1 either.
回答6:
For pre 1.7 i would say an equivalent to Integer.compare(x, y) is:
Integer.valueOf(x).compareTo(y);
回答7:
If you are using java 8, you can create Comparator by this method:
Comparator.comparingInt(i -> i);
if you would like to compare with reversed order:
Comparator.comparingInt(i -> -i);
回答8:
You can do this via the bit manipulation, something like this:
(~a - ~b) >>> 31 | -((a - b) >>> 31)
public static void main(String[] args)
{
int a = 107;
int b = 106;
check(a, b);
a = 106;
b = 106;
check(a, b);
a = 106;
b = 107;
check(a, b);
}
public static void check(int a, int b)
{
System.out.println((~a - ~b) >>> 31 | -((a - b) >>> 31));
}
OUTPUT:
1
0
-1
回答9:
If you need just logical value (as it almost always is), the following one-liner will help you:
boolean ifIntsEqual = !((Math.max(a,b) - Math.min(a, b)) > 0);
And it works even in Java 1.5+, maybe even in 1.1 (i don't have one). Please tell us, if you can test it in 1.5-.
This one will do too:
boolean ifIntsEqual = !((Math.abs(a-b)) > 0);