【问题标题】:Creating a comparator class for Java TreeSet为 Java TreeSet 创建一个比较器类
【发布时间】:2013-06-10 18:22:51
【问题描述】:

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

【问题讨论】:

    标签: java comparator treeset


    【解决方案1】:

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

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

    【讨论】:

    • 我忘记了实现和扩展之间的区别。谢谢
    【解决方案2】:

    如果检查构造函数签名-public TreeSet(Comparator&lt;? super E&gt; comparator),则参数类型为java.util.Comparator

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

    public class MessageSentTimestampComparer implements Comparator<Message> {
    

    【讨论】:

      猜你喜欢
      • 2019-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      相关资源
      最近更新 更多