when i execute this code,it produces output : [p, s]
output shows that it store in natural order
when i add l to it than execute it,output: [l, s, p]
it should be in natural order but it is not.why??
when i add a to it than produces the output:[a,l,p,s]
which is in natural order.why?
if i add w instead of a in code like
than its output is:[l, s, p, w]
and now again the output is not sorted.why??
and the offer method works same as the add method if i replace add with offer and it produces same output..
I do not understand how jvm works with these methods??and what is the difference between add and offer method???
Ankit Garg wrote:When you display a PriorityQueue directly or using iterator, the ordering of elements is not guaranteed. The natural ordering is only guaranteed for peek and offer methods. Checkout the javadocs for PriorityQueue class, you'll get your answer...
I tried this :
that resulted in [l,s,p] instead [l,p,s]
I am also confused with usage of offer() for NaturalOrder
Can you help me, please?
the offer()/add() methods only insert the element into the queue. If you want a predictable order you should use peek/poll which return the head of the queue.
Myself wrote:The natural ordering is only guaranteed for peek and offer methods.
I wrote the method name wrong, it should be peek and poll not offer. Anyway, you can search the forum for "PriorityQueue toString", this doubt was asked many times. The toString method of PriorityQueue doesn't return elements in sorted order...