简体   繁体   English

具有长值的TreeSet自定义比较器

[英]TreeSet custom comparator with long values

I have a TreeSet<MyObject> where MyObject has a method getID() . 我有一个TreeSet<MyObject> ,其中MyObject有一个方法getID()

The getID() method returns a long which I want to use to sort the MyObject s within the custom comparator of a TreeSet 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);

However the method compare must return an int and I'm comparing long s. 但是, compare方法必须返回一个int而我正在比较long Is there a way I can get around this? 有办法解决这个问题吗?

The magnitude of the difference is not important, simply that there is a difference. 差异的大小并不重要,只是存在差异。

long a0long = a0.getID();
long a1long = a1.getID();
if (a0long < a1long)
{
    return -1;
}

return a0long == a1long ? 0 : 1;

How about just using the Long object? 仅使用Long对象怎么样?

Long.compare(a0.getID(),a1.getID());

Java doc: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM