简体   繁体   English

为Java TreeSet创建比较器类

[英]Creating a comparator class for Java TreeSet

I have created a comparator class for Java's TreeSet function that I wish to use to order messages. 我为Java的TreeSet函数创建了一个比较器类,希望用于订购消息。 This class looks as follows 该类如下

public class MessageSentTimestampComparer
{
/// <summary>
/// IComparer implementation that compares the epoch SentTimestamp and MessageId
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>

public int compare(Message x, Message y)
{
    String sentTimestampx = x.getAttributes().get("SentTimestamp");
    String sentTimestampy = y.getAttributes().get("SentTimestamp");

    if((sentTimestampx == null) | (sentTimestampy == null))
    {
        throw new NullPointerException("Unable to compare Messages " +
                "because one of the messages did not have a SentTimestamp" +
                " Attribute");
    }

    Long epochx = Long.valueOf(sentTimestampx);
    Long epochy = Long.valueOf(sentTimestampy);

    int result = epochx.compareTo(epochy);

    if (result != 0)
    {
        return result;
    }
    else
    {
        // same SentTimestamp so use the messageId for comparison
        return x.getMessageId().compareTo(y.getMessageId());
    }
}
}

But when I attempt to use this class as the comparator Eclipse gives and error and tells me to remove the call. 但是,当我尝试将此类用作比较器时,Eclipse给出并出错,并告诉我删除该调用。 I have been attempting to use the class like this 我一直在尝试使用这样的课程

private SortedSet<Message> _set = new TreeSet<Message>(new MessageSentTimestampComparer());

I have also attempted to extend the MessageSentTimestampComparer as a comparator with no success. 我还尝试将MessageSentTimestampComparer扩展为比较器,但没有成功。 Can someone please explain what I am doing wrong. 有人可以解释我在做什么错。

Your MessageSentTimestampComparer doesn't implement Comparator . 您的MessageSentTimestampComparer没有实现 Comparator Try this: 尝试这个:

public class MessageSentTimestampComparer implements Comparator<Message> {
  @Override
  public int compare(Message x, Message y) {
    return 0;  // do your comparison
  }
}

If you check the constructor signatue - public TreeSet(Comparator<? super E> comparator) , the parameter type is java.util.Comparator . 如果检查构造函数签名- public TreeSet(Comparator<? super E> comparator) ,则参数类型为java.util.Comparator

So your comparator must implement the Comparator interface (for the compiler to not complain) as follows - 因此,您的比较器必须实现Comparator接口(以使编译器不要抱怨),如下所示:

public class MessageSentTimestampComparer implements Comparator<Message> {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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