Обновление Java PriorityQueue, когда его элементы изменяют приоритет

while IFS= read -r line; do
echo "$line"
done < somefile.txt

Это - хороший способ обработать файл линию за линией. Очистка IFS необходима для получения пробельных символов в передней стороне или конце строки. "-r" необходим для получения всех необработанных символов, включая обратные косые черты.

53
задан Raedwald 20 March 2015 в 02:50
поделиться

2 ответа

You have to remove and re-insert, as the queue works by putting new elements in the appropriate position when they are inserted. This is much faster than the alternative of finding the highest-priority element every time you pull out of the queue. The drawback is that you cannot change the priority after the element has been inserted. A TreeMap has the same limitation (as does a HashMap, which also breaks when the hashcode of its elements changes after insertion).

If you want to write a wrapper, you can move the comparison code from enqueue to dequeue. You would not need to sort at enqueue time anymore (because the order it creates would not be reliable anyway if you allow changes).

But this will perform worse, and you want to synchronize on the queue if you change any of the priorities. Since you need to add synchronization code when updating priorities, you might as well just dequeue and enqueue (you need the reference to the queue in both cases).

32
ответ дан 7 November 2019 в 08:51
поделиться

Я не знаю, существует ли реализация Java, но если вы часто меняете значения ключей, вы можете использовать кучу Фибонначи, амортизированная стоимость которой составляет O (1), чтобы уменьшить значение ключа. записи в куче, а не O (log (n)), как в обычной куче.

10
ответ дан 7 November 2019 в 08:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: