This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
As per K&B book PriorityQueue is in sorted by order but I have question here when first I added elements into priorityqueue and printed it worked fine but after adding another element into priorityqueue order got changed and am not able to predict answer for this can anyone explain me.
Now i have question if I get this type question in exam what ans i should give According K & B book the PQ is sorted.
Hello Babugouda, your question is interesting. Now let us assume you get a question that asks you if PriorityQueue is Sorted, your answer should be YES, this is because elements of a PriorityQueue MUST be mutually comparable meaning that the objects you add to the PriorityQueue MUST implement the Comparable interface. Thit is a FUNDAMENTAL characteristics of Sorted collections.
Lets assume that that you are asked the output of an iteration, your answer should be that it is NOT guaranteed. If you have any doubts you should go to the official java API http://download.oracle.com/javase/6/docs/api/ for more details. I already did that and this is what I discovered:
A.Does NOT permit insertion of non-comparable objects (doing so may result in ClassCastException). Answer to the first question.
B.The Iterator provided in method iterator() is NOT guaranteed to traverse the elements of the priority queue in any particular order. Answer to second question.
Thank you once again for your intelligent question! I have just learnt something new about PriorityQueues!.
In Your Pursuit Towards Certification, NEVER Give Up.
I also want to say in addition that in terms of iteration, HashSet behaves in a similar way as in PriorityQueue. It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. OUKC Oracle mock exams specifically has a question that tests your knowledge on the iteration order in HashSet, this means that you are likely to find a similar question in the real exams. So we now know the answer: