0

我为 Java 的 TreeSet 函数创建了一个比较器类,我希望用它来订购消息。这个类看起来如下

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());
    }
}
}

但是当我尝试使用这个类作为比较器时,Eclipse 给出了错误并告诉我删除调用。我一直在尝试像这样使用这个类

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

我还尝试将 MessageSentTimestampComparer 扩展为比较器,但没有成功。有人可以解释我做错了什么。

4

2 回答 2

5

MessageSentTimestampComparer没有实现 Comparator. 试试这个:

public class MessageSentTimestampComparer implements Comparator<Message> {
  @Override
  public int compare(Message x, Message y) {
    return 0;  // do your comparison
  }
}
于 2013-06-10T18:29:20.403 回答
1

如果检查构造函数signatue- public TreeSet(Comparator<? super E> comparator),则参数类型为java.util.Comparator

所以你的比较器必须实现Comparator接口(编译器不会抱怨)如下 -

public class MessageSentTimestampComparer implements Comparator<Message> {
于 2013-06-10T18:29:42.050 回答