Efficient compareTo () for primitive long

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

I do not look at the obvious naive implementation , but I wondered if there is an elegant single-line code (without creating a new Long (value)).

Maybe something like this:

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

Can someone verify what will work and / or suggest another implementation?

+5
source share
2 answers

One liner code for this:

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

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

+11
source

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

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

In general, I'm not sure that you can compare longs without branching instructions, because the difference in the two lengths might not correspond to the length without overflow, which would change the sign of the difference.

Therefore, I agree with Eugene that using a JDK implementation is probably the best approach.

+1
source

All Articles