Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I iterate a priority queue properly?

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?

like image 584
Anon Avatar asked Dec 07 '12 07:12

Anon


People also ask

Can we iterate priority queue?

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.

Can we iterate in priority queue C++?

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.

How do I avoid duplicates in priority queue?

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.

Can you iterate a 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++


3 Answers

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);
    }
like image 194
Haroldo_OK Avatar answered Oct 29 '22 17:10

Haroldo_OK


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
}
like image 28
The111 Avatar answered Oct 29 '22 18:10

The111


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()).

like image 38
Miljen Mikic Avatar answered Oct 29 '22 18:10

Miljen Mikic