我有一个NodeWeightWrapper
包装器来包装Node
对象及其关联的weight
。下面是包装器的代码。我在Comparable
上实现了compareTo
和重写weight
方法,因此我可以在优先级队列中使用包装器对象。
public class NodeWeightWrapper implements Comparable<NodeWeightWrapper> {
private final Node node;
private int weight;
public NodeWeightWrapper(Node node, int weight) {
this.node = node;
this.weight = weight;
}
public Node getNode() {
return node;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
@Override
public int compareTo(NodeWeightWrapper o) {
return Integer.compare(this.getWeight(), o.getWeight());
}
}
将对象添加到优先级队列
PriorityQueue<NodeWeightWrapper> freeNodes = new PriorityQueue<>();
freeNodes.add(new NodeWeightWrapper(nodeA, 20));
freeNodes.add(new NodeWeightWrapper(nodeB, 15));
freeNodes.add(new NodeWeightWrapper(nodeC, 10));
问题是,如果我更新优先级队列中对象的weight
,如下所示。下次我poll
优先级队列中的对象时,不会反映出相同的情况。这意味着优先级队列仅在发生新插入时对元素进行排序。所以我尝试删除原始包装器对象并插入一个具有更新值的新包装器对象但是抛出ConcurrentModificationException,因为我们处于foreach
循环中。任何可以进行重量更新的建议都会反映在优先级排队中。
for (NodeWeightWrapper nww : freeNodes) {
if (nww.getWeight() > value) {
nww.setWeight(value);
}
}
答案 0 :(得分:0)
PriorityQueue<NodeWeightWrapper> modified = new PriorityQueue<>();
for (NodeWeightWrapper nww : freeNodes) {
if (nww.getWeight() > value) {
nww.setWeight(value);
}
modified.add(mww)
}