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).
Does long long not support negative values ? Yes it does support negative values as long as it is not appended after unsigned .
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With