Comparators, Comparable and SortedList

To sort in Java, you must compare elements that are Comparable or create an external Comparator. By creating a Comparator or implementing Comparable, we gain full control of the sort order of our elements.

For the Issue class, you can sort using the priority field:

import java.util.Comparator;
// a simple issues library
import ca.odell.issuezilla.*;

/**
 * Compare issues by priority.
 * 
 * @author <a href="mailto:jesse@odel.on.ca">Jesse Wilson</a>
 */
public class IssueComparator implements Comparator {
  public int compare(Object a, Object b) {
    Issue issueA = (Issue)a;
    Issue issueB = (Issue)b;
    
    // rating is between 1 and 5, lower is more important
    int issueAValue = issueA.getPriority().getValue();
    int issueBValue = issueB.getPriority().getValue();
    
    return issueAValue - issueBValue;
  }
}

Now that you can compare elements, create a SortedList using the issues EventList and the IssueComparator. The SortedList will provide a sorted view of the issues list. It keeps the issues sorted dynamically as the source EventList changes.

SortedList sortedIssues = new SortedList(issuesEventList, new IssueComparator());