Java: priority queue

I have a java program that looks like

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 not sorting their priority queue. According to java specifications, it implements comparable ones and supports sort order (natural sort)

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

+7
source share
2 answers

Inserting a priority into the queue is not enough to sort the list of elements, because it does not store them in sorted order; he stores them in a partially sorted heap order. You must remove the elements in a loop to sort them:

 while (pq.size() > 0) System.out.println(pq.remove()); 
+7
source

It is sorted, but inside the items are stored in a heap . If you call peek() , poll() or remove() , you get the correct order (and how you access the queues).

+7
source

All Articles