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 on PriorityQueue? 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 on PriorityQueue?" Watch "Doubt on PriorityQueue?" New topic

Doubt on PriorityQueue?

Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

Can anyone explain me "PriorityQueue orders its elements using user-defined priority .The priority can be simple as natural ordering".

--Here what does it mean user-defined priority

--And when I run my program it produces:-
[1, 3, 6, 8, 4, 7]
[1, 3, 6, 8, 4, 7] //with the use of comparator

So that I think this is not any kind of ordering.please explain me

Seema Gaurav
Ranch Hand

Joined: Apr 29, 2008
Posts: 47
Interesting question Ashok, I thought this was strange too. I looked up the PriorityQueue API and this is what I found there:

Maybe that's the reason why printing 'q' or iterating through the queue doesn't display the order.

Having said that, I tried to poll the queue and it displays the correct order. Maybe polling is the way to go

Those were my 2 cents, any thoughts people?
[ October 07, 2008: Message edited by: Seema Gaurav ]
Ankit Garg

Joined: Aug 03, 2008
Posts: 9462

You are right Seema. When you use an PriorityQue object in System.out.println(), then the toString method of AbstractCollection class is executed.

The toString implementation in AbstractCollection class iterates through a collection and displays the output as [element1, element2,...]

But when you use poll() or peek(), then the elements are traversed in sorted order...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
I agree. Here's the link:
subject: Doubt on PriorityQueue?
jQuery in Action, 3rd edition