Removing top of PriorityQueue?

走远了吗. 提交于 2019-12-06 03:37:18

问题


Assume that I am using the PriorityQueue class from Java.util. I want to remove the largest number from the PriorityQueue pq, which we assume is at the head of the queue.

Will the following work?

// 1 
int head = pq.peek();
pq.dequeue(head);

// 2
int head = pq.dequeue(pq.peek());

Would this work the same for non-primitives as well?


回答1:


Queue#peek and Queue#element return the head value of the queue, Queue#poll and Queue#remove return and remove it.

It looks like

int head = pq.poll();

is what you want.

And: it will only work for non-primitive values because a queue will store objects only. The trick is, that (I guess) your queue stores Integer values and Java 1.5+ can automatically convert the results to int primitives (outboxing). So it feels like the queue stored int values.




回答2:


peek() - return but doesn't remove head value

poll() - return and remove head value

        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

        pq.add(2);pq.add(3);

        System.out.println(pq); // [2, 3]
        System.out.println(pq.peek()); // head 2
        System.out.println(pq); // 2 still exists. [2, 3]
        System.out.println(pq.poll()); // 2. remove head (2)
        System.out.println(pq); // [3]


来源:https://stackoverflow.com/questions/4488325/removing-top-of-priorityqueue

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