Java : Priority Queue

梦想的初衷 提交于 2019-12-19 17:38:25

问题


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]


回答1:


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




回答2:


Insertion into a priority queue is not enough to sort a list of elements, since it doesn't store them in sorted order; it stores them in the partially sorted heap order. You have to remove the elements in a loop to sort them:

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



回答3:


poll() and remove() will give sorted order not peek() as per java8.

 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);
        // Remove items from the Priority Queue (DEQUEUE)
        while (!pq.isEmpty()) {
          //  System.out.println(pq.remove());
          System.out.println(pq.poll());
        }
Output for poll() & remove():
1 
2
3 
4 
5 
6 
7 
8 
9 
10
output for peek():
1
1
1
1
1
1
1
1
1
1


来源:https://stackoverflow.com/questions/7927213/java-priority-queue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!