Convert long to int, keep positive / negative / 0

I want to implement java.util.Comparatorwith Long:

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

I have a solution with a statement ?::

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

But I wonder if there is another way to implement it.

(I tried return (int)(l1-l2), but it was wrong).

+5
source share
2 answers

This simple - Longitself provides an implementation:

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

On the other hand, at this moment I'm not sure why you have a custom comparator at all ...

EDIT: if you are actually comparing values Longand using Java 1.7, you can use Long.compare(long, long). Otherwise, complete the current implementation.

+12
source

, . . , java.lang.Long compareTo, , .

+2

All Articles