I would think that alphabetically one would come before six and that three would come before two - please explain these discrepancies.
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.
Sandra Bachan wrote:Based on the discussions on this forum, seems that you have to manually poll() or peek() to have queue printed in order, such as the code below (as)
1 2 3 4 5 6
This output is perfect only when numbers of Integer class or String class ex- "1" ,"8", "4","2" is considered & the putput wud still be orderd removal by poll()
But when PriorityQueue<String> pq ---->"Seventy", "Six ","One", " Two", like this unordered strings are loaded poll wud worka as deisred. I mean the output of using above code would not produce the ordered removal by pq.poll().
hence the question posed by Sandra Bachan is unanawered. As he/she wanted 2 then 4 to removed.
kindly forgive me if I'm wrong, but I too had the same question wherein I feel Priority Queue would not work for String of chars.
Abimaran Kugathasan wrote:For these question, as Ankit said, search it.
System.out.println is invoking the toString() method of the PriorityQueue, which is using the iterator, which is not guaranteed to respect the natural ordering. From the docs: "The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order."So when you print the PriorityQueue with System.out.println(), you won't get order(natural/yours). If you print them manually as Sandra did, you'll get the order!
but when pq.poll() method is called (with pq containing a string of char with String type safe) its supposed to remove the highest priority element in that priority queue isn'it?
will always give unordered output.
But in palce of one two, had I placed 1, 2,80,3,7 then the output is ordered just like how a ideal priorotyqueue as to work