Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Priority Queue

I have a java program which goes like this

public class PriorityQueueExample {

public static void main(String[] args) {
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
    pq.add(10);
    pq.add(1);
    pq.add(9);
    pq.add(2);
    pq.add(8);
    pq.add(3);
    pq.add(7);
    pq.add(4);
    pq.add(6);
    pq.add(5);
System.out.println(pq);

}

}

My Question is why does not the priority queue sort them. As per the java specs it implements comparable and maintains the sorting order(natural sorting)

My output of the program is as follows : [1, 2, 3, 4, 5, 9, 7, 10, 6, 8]

like image 262
Avinash Reddy Avatar asked Oct 28 '11 09:10

Avinash Reddy


1 Answers

It is sorted, but internally the elements are stored in a heap. If you call peek(), poll(), or remove(), you will get the right order (and that's how you access queues).

like image 87
Konrad Garus Avatar answered Sep 30 '22 14:09

Konrad Garus