[英]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.