简体   繁体   English

如何在Java中修改PriorityQueue的元素?

[英]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. 我得到了以下问题要解决:我使用特定对象的PriorityQueue,并且我用来与其他对象进行比较的属性设置为所有对象的相同值。

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. 我没有理解如何做到这一点,因为peek()和poll()只是删除并返回队列的头部,而remove()只是删除了对象,而这并不是我想要的。 I also don't know how could I use Iterator here as well. 我也不知道如何在这里使用Iterator。

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. 我只是想用Iterator获取我想要的元素,将它从队列中删除,修改它(如果我不想删除它)再次在队列中添加它。 Would it work? 会有用吗?

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. 我只是想用Iterator获取我想要的元素,将其从队列中删除,修改它(如果我不想删除它)再次在队列中添加它。 Would it work? 会有用吗?

It should work 1 . 它应该工作1

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. 注意,这种方法是O(N) ,其中N是队列长度。 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 . 1 - 实际上,对于某些队列实现,在迭代优先级队列时添加(返回)元素可能会导致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. javadoc似乎说PriorityQueue会给CME,但PriorityBlockingQueue不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM