I have a NodeWeightWrapper
wrapper to wrap Node
object and its associated weight
. Below is the code for wrapper. I have implemented Comparable
and overridden compareTo
method on weight
, so I can use wrapper objects in a Priority Queue.
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());
}
}
Adding objects to Priority Queue
PriorityQueue<NodeWeightWrapper> freeNodes = new PriorityQueue<>();
freeNodes.add(new NodeWeightWrapper(nodeA, 20));
freeNodes.add(new NodeWeightWrapper(nodeB, 15));
freeNodes.add(new NodeWeightWrapper(nodeC, 10));
Here is the problem, If I update weight
of an object in Priority Queue as shown below. The same is not reflected next time I poll
an object out of the Priority Queue. Which means Priority Queue sorts elements only when a new insertion takes place. So I tried removing the original wrapper object and inserted a new wrapper object with updated value but that throws ConcurrentModificationException as we are in a foreach
loop. Any suggestion who can I make weight updation be reflected in Priority Queue.
for (NodeWeightWrapper nww : freeNodes) {
if (nww.getWeight() > value) {
nww.setWeight(value);
}
}