Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a Comparator in Java that compares based on two variables

I want to create a comparator to operate such that a process with a lower arrival time will appear first in a sorting, and if two processes have the same arrival time, the one with the lower process id comes first in the sorting. I tried the following code, but it doesn't seem to be working. Does anyone see a flaw in it?

public class FCFSComparator implements Comparator<Process>
{
    public int compare(Process o1, Process o2)
    {
        int result = o1.getArrivalTime() - o2.getArrivalTime();

        if(result == 0)
        {
            return (o1.getPid() < o2.getPid()) ? -1 : 1;
        }
        else
        {
            return result;
        }
//        return (result != 0 ? result : o1.getPid() - o2.getPid());
    }
}

To be specific, given the processes as follows

pid = 0 arrival time = 10
pid = 1 arrival time = 30
pid = 2 arrival time = 15
pid = 3 arrival time = 15
pid = 4 arrival time = 66

I get the following ordering at the end

Pid = 0 arrival time = 10
Pid = 2 arrival time = 15
Pid = 1 arrival time = 30
Pid = 4 arrival time = 66
Pid = 3 arrival time = 15
like image 407
Varun Madiath Avatar asked Dec 21 '22 16:12

Varun Madiath


1 Answers

I can't find anything wrong with your comparator. Here is my test case:

public class TestComparator {

    static class Process {
        int pid;
        int arrivalTime;

        Process(int pid, int arrivalTime) {
            this.pid = pid;
            this.arrivalTime = arrivalTime;
        }

        @Override
        public String toString() {
            return "Process [pid=" + pid + ", arrivalTime=" + arrivalTime + "]";
        }
    }

    static class FCFSComparator implements Comparator<Process> {
        public int compare(Process o1, Process o2) {
            int result = o1.arrivalTime - o2.arrivalTime;

            if (result == 0) {
                return (o1.pid < o2.pid) ? -1 : 1;
            } else {
                return result;
            }
        }
    }

    public static void main(String[] args) {
        List<Process> processes = Arrays.asList(
                new Process(0, 10),
                new Process(1, 30),
                new Process(2, 15),
                new Process(3, 15),
                new Process(4, 66));

        Collections.sort(processes, new FCFSComparator());

        for (Process process : processes) {
            System.out.println(process);
        }

    }
}

Output:

Process [pid=0, arrivalTime=10]
Process [pid=2, arrivalTime=15]
Process [pid=3, arrivalTime=15]
Process [pid=1, arrivalTime=30]
Process [pid=4, arrivalTime=66]
like image 180
bruno conde Avatar answered Dec 29 '22 00:12

bruno conde