I have a problem with PriorityQueues, as I am convinced that he orders a priority, but I am not sure what the priority is (I mean what the value is and where it comes from). PriorityQueue can be done using a comparator in the constructor, and I tried this, but it does not work.
Queue Class:
public JavaPriorityFlightQueue() { super(); flights = new PriorityQueue(5, new SortQueueViaPriority()); }
Comparator:
import java.util.Comparator; public class SortQueueViaPriority implements Comparator { public int compare(Object o1, Object o2){ Flight f1 = (Flight) o1; Flight f2 = (Flight) o2; if( f1 == null || f2 == null ){ if( f1 == f2 ) return 0; else if( f2 == null) return +1; else return -1; } Integer i1 = (Integer) f1.getPriority(); Integer i2 = (Integer) f2.getPriority(); return i2.compareTo(i1); } }
Priority is an int value that is part of the flight class. I check it out.
JavaPriorityFlightQueue flightQueue = new JavaPriorityFlightQueue(); Flight flight1 = new Flight("0001",9); Flight flight2 = new Flight("0002",7); Flight flight3 = new Flight("0003",1); Flight flight4 = new Flight("0004",2); Flight flight5 = new Flight("0005",1);
However, the PriorityQueue is not sorted, and when I check it, the value 9 is never compared to anything, and the result is not sorted. the comparison class SortQueueViaPriority is copied and pasted from another class where the class is perfectly sorted.
source share