我想知道一旦某个对象被移除并重新插入队列以更新其优先级,是否仍然可以维持优先级队列中对象的优先级?
我这样做的方法是,我从优先级队列中删除对象,然后将更新后的对象重新放入队列中。但是,这会破坏我使用 Comparator
比较器
:
class PriorityValueComparator implements Comparator<Human>{
public int compare(Human x, Human y){
return y._priority - x._priority;
}
}
例如,
insert in the following order: John, Alex, Kerby, Jane
The priority queue is in the following form: [Jane, 100], [Kerby, 59], [Alex, 33], [John, 13]
Update John to 100
[John, 100] (since John is inserted before Jane), [Jane, 100], [Kerby, 59], [Alex, 33]
更新:
或者,在 Human 类中,可以添加静态属性 time
。在 Human 的构造函数中,
public Human() {
//add in whatever you want here
time++; //This will ensure that every elements will have their own unique order number
}
最佳答案
优先级队列实现允许在具有相同优先级的元素之间任意选择。如果你想强制一个特定的顺序,那么你需要改变比较器。假设您维护一个字段 _insertion_time
,以便较早插入的人具有较小的非负值,那么您可以将比较器重写为
class PriorityValueComparator implements Comparator<Human>{
public int compare(Human x, Human y){
if (y._priority != x._priority) return y._priority - x._priority;
else return y._insertion_time - x._insertion_time;
}
}
关于java - 一旦一个对象被取出来更新它的优先级,如何保持一个对象在优先级队列中的优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755899/