aspose file tools*
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
Author

PriorityQueue

Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
Hi

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
FIVE
four
five
two
one
three

0
30
1
200
33

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]


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3014
    
  10
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: http://aspose.com/file-tools
 
subject: PriorityQueue