[英]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.