删除PriorityQueue的顶部?

Kir*_*ira 5 java queue priority-queue

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

以下工作会吗?

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

// 2
int head = pq.dequeue(pq.peek());
Run Code Online (Sandbox Code Playgroud)

对于非原始的人来说,这也是一样的吗?

And*_*s_D 9

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

看起来像

int head = pq.poll();
Run Code Online (Sandbox Code Playgroud)

是你想要的.

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


小智 5

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]
Run Code Online (Sandbox Code Playgroud)