File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes PriorityQueue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "PriorityQueue" Watch "PriorityQueue" New topic


Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385

I have a doubt about the priority Queue in JDK 1.6

I know it keeps the element in order either in natural order or by comparator

But when i use the for each loop i can not under stand the output it produces .Please see the code below

if i run the above code the output is


As you can see none of the output is in natural order.However if use TreeSet then, for each displays the output in natural order.

Also if use pool,peek or remove the ouput depends on the natural order and i can get the correct output i.e. if i use poll() in Integer Queue the output is 0 for the first time and 1 for the second time.

Then why does it fail to display the element in order when for each loop is used?

[NK: Added code tags. Please UseCodeTags while posting code]


Failure is not an option.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
Take a look at the PriorityQueue API:
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).

The reason for this is that a PriorityQueue is optimized for fast insertion and retrieval of elements, but not for iteration. It knows how to organize its data internally so that every time you call poll() or peek(), it will get the correct highest-priority element. But in order to iterate the entire tree (without actually removing anything from the queue), going in order would require additional work that would slow down the other operations. They chose instead to give you a fast iterator that isn't necessarily correct in order, rather than a slower iterator that iterates in order. So if you care about the order, don't use the iterator.
I agree. Here's the link:
subject: PriorityQueue
It's not a secret anymore!