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?
The remove() method of PriorityQueue class of java. util package is used to remove a particular element from a PriorityQueue.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With