I have a java assignment involving iterating a priority queue. The queue consists of objects with a string and an int in them and i need to have a way to check a seperate object's string against all the objects in the queue.
Would it be best way to do this be an iterator object? That seems too messy. I could dequeue and enqueue but that seems inefficient. Maybe a foreach loop?
PriorityQueue. iterator() method is used to return an iterator of the same elements as the Priority Queue. The elements are returned in random order from what present in the Queue.
Similar answer for a priority queue: no, you cannot. In this case though, a vector is used by default. In neither case can you access the underlying container to iterate over them.
A PriorityQueue in Java does not have any restriction with regard to duplicate elements. 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.
We can iterate on queue using std: :front which will return the front element of the queue and std: :pop which will remove the front element of the queue. But, after iterating on the queue with this method queue will vanish as we are deleting elements of the queue as we iterate over it. Example: C++
One small detail: if there's any chance your queue could be modified during the loop, then both iterator
and for each
will cause a ConcurrentModificationException
; if there's a chance the queue will get modified during the processing, you could use poll()
:
Resource resource;
while ((resource = resourceQueue.poll()) != null) {
this.processIncludes(resourceQueue, resource);
}
Yes, if you need to check every single element in the collection, an iterator
or for each
is probably best.
Iterator<E> iter = myPriorityQueue.iterator();
while (iter.hasNext()) {
current = iter.next();
// do something with current
}
Or
for (Element e : myQueue) {
// do something with e
}
If you don't care about ordering (in that case - why are you dealing with PriorityQueue
?), use Iterator. If you want to iterate by priority, then see the advice from Javadoc:
If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
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