java - 为 Java TreeSet 创建比较器类

标签 java comparator treeset

我已经为 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 扩展为比较器,但没有成功。有人可以解释一下我做错了什么吗?

最佳答案

您的 MessageSentTimestampComparer实现 Comparator 。试试这个:

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

关于java - 为 Java TreeSet 创建比较器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17030347/

相关文章:

java - 将多个字符串的不同子字符串添加到 Treeset

java - 带商的 if 语句不起作用

java - 在 Android 中使用 intent 共享图像文件时无法打开文件进行共享?

Java,反射,从类中获取方法

java - 有没有一种通过枚举实现多个比较器的好方法?

java - 在 Java 中向 TreeSet 中的迭代器添加自定义方法

java - 努力在破折号之间打印空格

java - 如何在同一个 FloatingActionButton 上隐藏/显示不同的操作,就像在 Inbox 应用程序中一样

java - 使用比较器接口(interface)时出错

java - 我可以在不实现 Comparable 的情况下使用 Comparator 吗?