簡體   English   中英

為Java TreeSet創建比較器類

[英]Creating a comparator class for Java 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
  }
}

如果檢查構造函數簽名- public TreeSet(Comparator<? super E> comparator) ,則參數類型為java.util.Comparator

因此,您的比較器必須實現Comparator接口(以使編譯器不要抱怨),如下所示:

public class MessageSentTimestampComparer implements Comparator<Message> {

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM