简体   繁体   中英

Custom comparator isn't sorting

I'm trying to simulate a CPU scheduler. I have an ArrayList of a Process class I made. I'm trying to sort this array list by the arrival time of the process. I must be missing something, because when I print my ArrayList , nothing happens.

I've been looking through other users posts but I haven't found anything that made sense to me.

Here is my Comparator and call to sort :

class ArrivalTimeComparator implements Comparator<Process> {
    @Override
        public int compare(Process p1, Process p2) {
        return (int) (p1.getArrivalTime()-p2.getArrivalTime());
    }
}

Collections.sort(processArray, new ArrivalTimeComparator());

This code

(int)(p1.getArrivalTime()-p2.getArrivalTime())

may suffer from integer operation overflow, thus you can get odd results. If you're using Java 7, use

Integer.compare(p1.getArrivalTime(), p2.getArrivalTime()); //or Long.compare

If you're working with Java 6 or less:

return p1.getArrivalTime() > p2.getArrivalTime() ? 1 : p1.getArrivalTime() < p2.getArrivalTime() ? -1 : 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM