0
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.

user1817988
  • 237
  • 2
  • 5
  • 11
  • 1
    Pls check this http://stackoverflow.com/questions/683041/java-how-do-i-use-a-priorityqueue – Akhil K Nambiar Nov 12 '12 at 12:11
  • The next value from a PriorityQueue is always the lowest. If you constructor the PriorityQueue with the right Comparator you shouldn't need additional sorting. – Peter Lawrey Nov 12 '12 at 12:22

2 Answers2

3

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

PermGenError
  • 45,977
  • 8
  • 87
  • 106
  • I see so I cannot sort a Queue? – user1817988 Nov 12 '12 at 12:12
  • Comparator super E> comparator() Returns the comparator used to order the elements in this queue, or null if this queue is sorted according to the natural ordering of its elements. – user1817988 Nov 12 '12 at 12:18
  • This was in the priorityqueue doc, what is this Comparator exactly and what is it/can it be used for? – user1817988 Nov 12 '12 at 12:19
  • Comparator is an interface in java.util package which is used to custom sort. you could also use that constructor of the priority queue to sort it based on the comparator. – PermGenError Nov 12 '12 at 12:21
0

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.

The Cat
  • 2,375
  • 6
  • 25
  • 37