my dog learned polymorphism
The moose likes Java in General and the fly likes Offer VS add Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Offer VS add" Watch "Offer VS add" New topic

Offer VS add

Sudhanshu Mishra
Ranch Hand

Joined: May 28, 2011
Posts: 229

Hi all,
I have a code which inserts the elements in the priority queue using offer and add method.I am just unable to figure out the order of sorting.
The code is

Now,why does 7 comes before 4 and 6 if the priority queue maintains the natural order.
Please guide me through...
Rob Spoor

Joined: Oct 27, 2005
Posts: 19905

From the Javadoc of its iterator() method, which is used internally when printing:
Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.

This is also said in the class' main Javadoc:
he 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 priority is only guaranteed for poll(), peek(), remove() and element().

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Offer VS add