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 Offer VS add Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide 1Z0-808 this week in the OCAJP forum!
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: 220

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: 19845

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