删除 PriorityQueue 的顶部?

发布于 2024-10-08 18:17:39 字数 239 浏览 1 评论 0原文

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

下面的工作会起作用吗?

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

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

这对于非基元也同样有效吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

歌枕肩 2024-10-15 18:17:39

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

看起来

int head = pq.poll();

就是你想要的。

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

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.

咿呀咿呀哟 2024-10-15 18:17:39

peek() - 返回但不删除头值

poll() - 返回并删除头值

        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]

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]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文