[英]TreeSet custom comparator with long values
我有一个TreeSet<MyObject>
,其中MyObject
有一个方法getID()
。
getID()
方法返回一个long
,我想使用它对TreeSet的自定义比较器中的MyObject
进行排序
Comparator<MyObject> comparator = new Comparator<MyObject>() {
public int compare(MyObject a0, MyObject a1) {
return a0.getID()-a1.getID();
}
};
TreeSet<MyObject> set = new TreeSet<MyObject>(comparator);
但是, compare
方法必须返回一个int
而我正在比较long
。 有办法解决这个问题吗?
差异的大小并不重要,只是存在差异。
long a0long = a0.getID();
long a1long = a1.getID();
if (a0long < a1long)
{
return -1;
}
return a0long == a1long ? 0 : 1;
仅使用Long对象怎么样?
Long.compare(a0.getID(),a1.getID());
Java文件:
public static int compare(long x,long y)
Compares two long values numerically. The value returned is identical to what would be returned by:
Long.valueOf(x).compareTo(Long.valueOf(y))
Parameters:
x - the first long to compare
y - the second long to compare
Returns:
the value 0 if x == y; a value less than 0 if x < y; and a value greater than 0 if x > y
Since:
1.7
您可以一行完成:
return Long.valueOf(a0.getID()).compareTo(Long.valueOf(a1.getID()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.