Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effective compareTo() for primitive long

Tags:

java

compareto

Working on a sorted list I came to a point I needed to implement a compareTo() function for primitive long values.

I'm not looking for the obvious naive implementation, but was wondering if there's an elegant one-liner code to do that (without creating a new Long(value)).

Maybe something like this:

@Override public int compareTo(MyClass that) {
    return (int) ((value - that.value) >>> 32);
}

Can anyone verify that would work and/or suggest another implementation?

like image 737
traveh Avatar asked Jun 28 '15 14:06

traveh


People also ask

Can we use == to compare long in Java?

equals() instead of the reference comparison operator (==). This is because Java maintains a constant pool for instances of Long between -128 and 127. This optimization, though, does not give us a license to use ==.

Can we compare two long values in Java?

The java. lang. Long. compareTo() method compares two Long objects numerically.

How do you compare two long variables in Java?

equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Long object that contains the same long value as this object. It returns false if both the objects are not same.


2 Answers

One liner code to that:

int res = Long.compare(long x, long y) 

Your code wont work correctly for all values, try it for Integer.MIN_VALUE - Integer.MAX_VALUE and you will get +1

like image 164
Evgeniy Dorofeev Avatar answered Oct 25 '22 10:10

Evgeniy Dorofeev


Your algorithm is incorrect, as it returns 0 when asked to compare 1 and 0:

(1 - 0) >>> 32
1 >>> 32
0

In general, I am not sure it is possible to compare longs without branch instructions, because the difference of two longs may not fit in a long without overflowing, which would change the sign of the difference.

I therefore agree with Evgeniy's answer that using the JDK implementation is likely the best approach.

like image 36
meriton Avatar answered Oct 25 '22 10:10

meriton