Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing top of PriorityQueue?

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?

like image 294
Kira Avatar asked Dec 20 '10 09:12

Kira


People also ask

How do you remove the top element of the priority queue?

The remove() method of PriorityQueue class of java. util package is used to remove a particular element from a PriorityQueue.

Can we remove particular element from priority queue?

remove() method is used to remove the single instance of a particular element from the PriorityQueue . The PriorityQueue. remove() method is present in the PriorityQueue class inside the java.

Which element is removed first in priority queue?

The front of the priority queue contains the least element according to the specified ordering, and the rear of the priority queue contains the greatest element. So when you remove an element from the priority queue, the least element according to the specified ordering is removed first.

How do I remove duplicates in priority queue?

If you want to ensure that two identical items are never present in the priority queue at the same time the simplest way would be to maintain a separate Set in parallel with the priority queue.


1 Answers

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.

like image 62
Andreas Dolk Avatar answered Sep 19 '22 22:09

Andreas Dolk