Java Priority Queue无法按预期工作

时间:2014-10-23 09:43:39

标签: java data-structures priority-queue

我有一个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);
     }
}

1 个答案:

答案 0 :(得分:0)

PriorityQueue<NodeWeightWrapper> modified = new PriorityQueue<>();
for (NodeWeightWrapper nww : freeNodes) {
 if (nww.getWeight() > value) {
     nww.setWeight(value);
 }
 modified.add(mww)
}