Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert long to int, keep positive/negative/0

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).

like image 702
Freewind Avatar asked Apr 11 '12 13:04

Freewind


People also ask

Can long hold negative values?

Does long long not support negative values ? Yes it does support negative values as long as it is not appended after unsigned .

How do you turn an integer into a negative?

An alternative approach is to use multiply by -1 . To convert a positive number to a negative number, multiply the number by -1 , e.g. 5 * -1 .

Can negative numbers be stored in int?

In most implementations that you are likely to encounter, negative signed integers are stored in what is called two's complement. The other major way of storing negative signed numbers is called one's complement. The one's complement of an N-bit number x is defined as x with all its bits flipped, basically.


1 Answers

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.

like image 91
Jon Skeet Avatar answered Sep 18 '22 20:09

Jon Skeet