我有一个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
s。有没有办法解决这个问题?
答案 0 :(得分:2)
差异的大小并不重要,只是存在差异。
long a0long = a0.getID();
long a1long = a1.getID();
if (a0long < a1long)
{
return -1;
}
return a0long == a1long ? 0 : 1;
答案 1 :(得分:2)
如何使用Long对象?
Long.compare(a0.getID(),a1.getID());
Java doc:
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
答案 2 :(得分:0)
您可以在一行中完成:
return Long.valueOf(a0.getID()).compareTo(Long.valueOf(a1.getID()));