Search code examples
javacompareto

Effective compareTo() for primitive long


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?


Solution

  • 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