本文介绍了删除 PriorityQueue 的顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用 Java.util 中的 PriorityQueue 类.我想从 PriorityQueue pq 中删除最大的数字,我们假设它位于队列的头部.

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.

以下是否有效?

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

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

这对非原语也一样吗?

推荐答案

Queue#peekQueue#element 返回队列的头部值,Queue#pollQueue#remove 返回并删除它.

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

看起来像

int head = pq.poll();

就是你想要的.

而且:它适用于非原始值,因为队列只存储对象.诀窍是,(我猜)您的队列存储 Integer 值,Java 1.5+ 可以自动将结果转换为 int 原语(发件箱).所以它感觉就像队列存储了int值.

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.

这篇关于删除 PriorityQueue 的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 01:43