5

I want to implement a java.util.Comparator with Long:

new Comparator<Long>() {
    public int compare(Long l1, Long l2) {
        // (*)
    }
}

I have a solution with operator ?::

return l1==l2 ? 0 : (l1>l2 ? 1 : -1);

But I wonder if there is any other way to implement it.

(I was trying return (int)(l1-l2), but it's incorrect).

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 1
    Why would you want to alter your implementation? It is correct. – dtech Apr 11 '12 at 13:18
  • 1
    `return (int)Math.signum(l1-l2)` ? – assylias Apr 11 '12 at 13:24
  • @assylias You're then converting a long to a double, and a double back to a int again. Also that solution might not be correct for all long's (e.g. return 0 on 2^60 and 2^60-1) – dtech Apr 11 '12 at 13:26
  • @dtech clearly not efficient, but was in response to "(I was trying return (int)(l1-l2), but it's incorrect)." – assylias Apr 11 '12 at 13:27

2 Answers2

12

That's easy - Long itself provides an implementation:

public int compare(Long l1, Long l2) {
    return l1.compareTo(l2);   
}

On the other hand, at that point I'm not sure why you've got a custom comparator at all...

EDIT: If you're actually comparing long values and you're using Java 1.7, you can use Long.compare(long, long). Otherwise, go with your current implementation.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you, it's a simplified demo of my real problem. But I just found, what I need to compare is `long`s, not `Long`s, so I have to still use `?:` – Freewind Apr 11 '12 at 13:22
  • @FreeWind Java has autoboxing since 1.6 so it doesn't matter. long and Long can be used interchangedly in method signatures. Or you can just use `new Long(long value)` – dtech Apr 11 '12 at 13:25
  • Your answer is still the best for this question :) – Freewind Apr 11 '12 at 13:35
2

No, that is the only valid way to do so. This topic is already discussed a lot of times. Of course, java.lang.Long implements already a compareTo function, but it has exactly the same implementation as you have.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • Finally I still use `?:`, but since in this question it's `Long`, so I have to choose JonSkeet's answer. Thank you! – Freewind Apr 11 '12 at 13:37