Mr Guliarte
Mr Guliarte

Reputation: 739

How can I modify an element of a PriorityQueue in Java?

I got the following issue to solve: I'm with a PriorityQueue of a specific object, and the attribute I use to compare it with others are set with the same value for all the objects.

The problem is: I need to modify one of it's objects (I mean, find it by another attribute, and modify the comparable attribute) and take it off of the queue. And I got no ideia of how to do it, since peek() and poll() just remove and return the head of the queue, and remove() just remove the object, and it's not exactly what I want. I also don't know how could I use Iterator here as well.

That's the code I got until now:

public void inicializaDijkstra(Grafo grafo, Vertice v0){

    Comparator<Grafo> comparator = new verticecomparator();
    PriorityQueue<Grafo> Queue = new PriorityQueue<Grafo>(grafo.getNumeroDeVertices,grafo);
    for (Vertice vertice : conjuntoDeVertices) {
        queue.add(vertice);

}

I just though of gettinng the element I want with the Iterator, remove it from the queue, modify it and (if I didn't want to remove it) add it again on the queue. Would it work?

Upvotes: 3

Views: 2163

Answers (1)

Stephen C
Stephen C

Reputation: 719739

I just thought of getting the element I want with the Iterator, remove it from the queue, modify it and (if I didn't want to remove it) add it again on the queue. Would it work?

It should work1.

Indeed, I can't think of a better / more efficient way of doing this given your data structure choices.

Note that this approach is O(N) where N is the queue length. In a multi-threaded context you would probably need to do the entire sequence under an exclusive lock, and that could make it a concurrency bottleneck.


1 - Actually, with some queue implementations, adding (back) an element while you are iterating the priority queue can result in a ConcurrentModificationException. If that is a problem, then you may need to make a list of elements that need re-inserting and then re-insert them after the you have finished iterating. The javadocs seem to say that PriorityQueue would give CME's but PriorityBlockingQueue would not.

Upvotes: 2

Related Questions