Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a PriorityQueue allow elements already within the queue to be reordered?

I want to augment or lower the priority of items in a PriorityQueue: for example, I might be downloading a long list of images and suddenly want the thirtieth one to have highest priority.

As I understand it, poll() always returns the queue object with the lowest value (as determined by a comparator). If I can lower the value of an item already in a queue (e.g. if this value is determined by an int in the object and I reduce the int value in some other function), will it be returned first by poll(), or is the sorting that allows poll() to do this done at insert time (e.g. by bubbling new queue elements down a list till they reach their "natural" depth)?

If this is done on a PriorityBlockingQueue, could it cause concurrency issues?

like image 586
Andrew Wyld Avatar asked May 08 '26 16:05

Andrew Wyld


1 Answers

None of the collections in Java automatically reorders elements if you change the property that determine their order. For collections that depend on the .hashCode() , .equals() or some comparator, you are not allowed to change the object while it resides in the collection so that the hashcode/equals or comparator would yield different values.

You have to remove, change, re-insert the object if you want to change its priority within a PriorityQueue.

like image 154
nos Avatar answered May 11 '26 05:05

nos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!