[英]Convert long to int, keep positive/negative/0
I want to implement a java.util.Comparator
with Long
: 我想用Long
实现一个java.util.Comparator
:
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). (我正在尝试return (int)(l1-l2)
,但这是不正确的)。
That's easy - Long
itself provides an implementation: 这很简单 - Long
本身提供了一个实现:
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)
. 编辑:如果您实际上正在比较long
值并且您正在使用Java 1.7,则可以使用Long.compare(long, long)
。 Otherwise, go with your current implementation. 否则,请使用当前的实现。
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. 当然, java.lang.Long
已经实现了compareTo函数,但它具有与您完全相同的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.