我已经为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扩展为比较器但没有成功。有人可以解释我做错了什么。
答案 0 :(得分:5)
您的MessageSentTimestampComparer
没有实施 Comparator
。试试这个:
public class MessageSentTimestampComparer implements Comparator<Message> {
@Override
public int compare(Message x, Message y) {
return 0; // do your comparison
}
}
答案 1 :(得分:1)
如果检查构造函数签名 - public TreeSet(Comparator<? super E> comparator)
,则参数类型为java.util.Comparator
。
所以你的比较器必须实现Comparator
接口(编译器不要抱怨),如下所示 -
public class MessageSentTimestampComparer implements Comparator<Message> {