views:

642

answers:

2

java.util.PriorityQueue allows a Comparator to be passed at construction time. When inserting elements, they are ordered according to the priority specified by the comparator.

What happens when the priority of an element changes after it has been inserted? When does the PriorityQueue reorder elements? Is it possible to poll an element that does not actually have minimal priority?

Are there good implementations of a priority queue which allow efficient priority updates?

+6  A: 

I would expect the PriorityQueue to not reorder things - and it could get very confused if it tries to do a binary search to find the right place to put any new entries.

Generally speaking I'd expect changing the priority of something already in a queue to be a bad idea, just like changing the values making up a key in a hash table.

Jon Skeet
It would be really helpful for some algorithms (e.g. Dijkstra's Algorithm) to be able to change the priority of something already in the queue.
D-Bug
But there'd have to be a notification of that. You could fake this up without any help from PriorityQueue by removing and re-adding the item if it changes priority.
Jon Skeet
@Jon correct me if I'm wrong, but I believe removing is O(n) for sun's implementation, so this ends up being O(n log n), whereas if you could update internally it would just be O(log n). It would seem like the ability to force an update would be nice.
Alex Beardsley
@Nalandial: Yes, you're right - it feels to me like for larger queues a tree implementation would be faster...
Jon Skeet
+8  A: 

You should remove the element, change it, and re-insert, since ordering occurs when it is inserted. Although it involves several steps, it is efficient.

One problem is that it will re-order when you remove the element, which is redundant if you are just going to re-insert it a moment later. If you implement your own priority queue from scratch, you could have an update() that skips this step, but extending the class won't work because you are still limited to the remove() and add() provided by the base.

James M.