Comparators, Comparable and SortedList

In order to do sorting in Java, we must be able to do comparisons with either a Comparator utility class or with elements that implement the Comparable interface. By writing Comparators (or implementing Comparable), we gain full control of the sort order of our elements.

In our Issue class, we have decided to sort using the ID field as the only criteria.

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 the SortedList can compare elements, we can simply create a SortedList using the source list and Comparator as the constructor argument. The SortedList will provide a sorted view of the original list even as the original list is modified.

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