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

doubt in offer()

aslika bahini
Ranch Hand

Joined: Mar 03, 2007
Posts: 111

I have a doubt in offer().
is this method add elements to the PriorityQueue in an order?
for eg :

Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
No, you're wrong.

add() and offer() in a priority queue do the same.

The priority queue is ordered, but not from the sequence, you put the elements in. It is ordered by natural order of the elements.

if you just iterate the queue, the output might be the same as the sequence of input.
The order can be seen only if you poll the elements out individually.

If you want to retain the order of your array, you shouldn't use a priority queue at all. Take a linked list.

Example (change offer to add and retry):

Try it.


all events occur in real time
I agree. Here's the link:
subject: doubt in offer()
It's not a secret anymore!