This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

doubt in offer()  RSS feed

 
aslika bahini
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hai,

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


Thanks
samura
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you're wrong.

First:
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.

Trap:
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.


Second
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.


Yours,
Bu.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!