Reputation: 235
public class Flight implements Comparable {
....
public int compareTo(Object obj){
Flight f = (Flight) obj;
Integer i1 = (Integer) f.priority;
Integer i2 = (Integer) priority;
if(f == null)
return 1;
else
return i2.compareTo(i1);
}
....
public class JavaPriorityFlightQueue {
public PriorityQueue flights;
....
public void joinQueue(Flight f){
flights.add(f);
Collections.sort(flights);
}
.....
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method sort(List) in the type Collections is not applicable for the arguments (PriorityQueue)
at section3.JavaPriorityFlightQueue.joinQueue(JavaPriorityFlightQueue.java:31)
at section3.FlightTest003.main(FlightTest003.java:19)
I used the exact same compareTo for a LinkedList and it works, and everything is the same I have not missed something out (I think). I do not understand how it works for LinkedList but not PriorityQueue.
Upvotes: 0
Views: 2833
Reputation: 46398
Collections.sort(List<E>)
only accepts List implementing classes.
java.util.LinkedList implemnts List inteface, where as Priorityqueue doesnt implement List.
Example:
PriorityQueue<String> pq = new PriorityQueue<String>();
Collections.sort(pq);//compiler error here sort expects a List not priorityQueue
check Collections.sort(List) signature
one way to sort a priority queue using Sort method is to convert priorityqueue to Array and use Arrays.sort().
Arrays.sort(pq.toArray());
or use a constructor of PQ which takes Comparator as an second argument.
PriorityQueue pq = new PriorityQueue(initialcapacity, Comparator);
and read about java.util.Comparator
Upvotes: 3
Reputation: 2475
Collections.sort
can only take a list as an argument, which doesn't really make sense as it is in the Collections
class. Sadly although PriorityQueue
is a Collection
, it does not implement List
.
Upvotes: 0