0

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);
     }
}
Meena Chaudhary
  • 9,909
  • 16
  • 60
  • 94
  • 1
    Insert a new object, like you're trying. Just don't do it in a way that will cause a `ConcurrentModificationException` to be thrown (i.e. not inside a foreach loop). – Kayaman Oct 23 '14 at 09:48
  • One suggestion is to build a new priorityQueue while you are traversing the original. – Suresh Sajja Oct 23 '14 at 09:51
  • You need to ensure that you don't modify the code mid-loop. Copy it into a list for later inclusion – User27854 Oct 23 '14 at 09:52
  • @Kayaman But removing and adding objects will take O(logn) time. Is that an efficient way to achieve updating. – Meena Chaudhary Oct 23 '14 at 10:07

1 Answers1

0
PriorityQueue<NodeWeightWrapper> modified = new PriorityQueue<>();
for (NodeWeightWrapper nww : freeNodes) {
 if (nww.getWeight() > value) {
     nww.setWeight(value);
 }
 modified.add(mww)
}
Suresh Sajja
  • 552
  • 3
  • 8
  • Isn't copying objects from old Priority Queue to new Priority Queue has a time complexity of O(nlogn). Is that an efficient way to do this ? – Meena Chaudhary Oct 23 '14 at 10:08
  • Idea is to remove the nww from priority queue, modify it, add it back. When you do this for all n elements, you are more or less constructing a new PQ. given this scenario, it is efficient to do with complexity o(nlogn). – Suresh Sajja Oct 24 '14 at 07:27