0

I have created a comparator class for Java's TreeSet function that I wish to use to order messages. This class looks as follows

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());
    }
}
}

But when I attempt to use this class as the comparator Eclipse gives and error and tells me to remove the call. I have been attempting to use the class like this

private SortedSet<Message> _set = new TreeSet<Message>(new MessageSentTimestampComparer());

I have also attempted to extend the MessageSentTimestampComparer as a comparator with no success. Can someone please explain what I am doing wrong.

2 Answers 2

5

Your MessageSentTimestampComparer doesn't implement Comparator. Try this:

public class MessageSentTimestampComparer implements Comparator<Message> {
  @Override
  public int compare(Message x, Message y) {
    return 0;  // do your comparison
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I forgot the difference between implements and extends. Thanks
1

If you check the constructor signatue - public TreeSet(Comparator<? super E> comparator), the parameter type is java.util.Comparator.

So your comparator must implement the Comparator interface (for the compiler to not complain) as follows -

public class MessageSentTimestampComparer implements Comparator<Message> {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.