compareTo with primitives -> Integer / int

荒凉一梦 提交于 2019-11-28 18:06:09
Peter Lawrey

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.

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

Johan Sjöberg

May I propose a third

((Integer) a).compareTo(b)  

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); 

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.

For pre 1.7 i would say an equivalent to Integer.compare(x, y) is:

Integer.valueOf(x).compareTo(y);

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);

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!