Search code examples
javapriority-queue

How to use the Comparator method in my project


I am creating an issue tracker in Java.I have an issue class as follows:

import java.util.Date;
public class Issue {

    int IssueNo;
    String IssueTitle;
    String text;
    Date TimeStamp=new Date();
    String Creator;
    String Assignee;
    String tag;
    int priority;
    String status;

}

My program has to display the issues based on either the priority(a number from 1 to 9) or TimeStamp(date on which issue is created).I want to know how to use priority queue and comparator to display the issues


Solution

  • Comparator has one method:

    int compareTo(T a, T b)
    

    where returning a negative int means a is bigger, a positive int means b is bigger, and 0 means equal

    So for doing multi-factor comparisons (as you are doing), start with priority.

    int priorityCompare = ((Issue)b).priority - ((Issue)a).priority;
    

    if priorityCompare is not 0, return priorityCompare. If it is 0, then move onto the next point of comparison (date) and so on until you've found a comparison point that differs, or all points are equal, in which case return 0;