如何在Java中修改PriorityQueue的元素?(How can I modify an element of a PriorityQueue in Java?)
我得到了以下问题要解决:我使用特定对象的PriorityQueue,并且我用来与其他对象进行比较的属性设置为所有对象的相同值。
问题是:我需要修改其中一个对象(我的意思是,通过另一个属性找到它,并修改可比属性)并将其从队列中删除。 我没有理解如何做到这一点,因为peek()和poll()只是删除并返回队列的头部,而remove()只是删除了对象,而这并不是我想要的。 我也不知道如何在这里使用Iterator。
那是我到现在为止的代码:
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); }
我只是想用Iterator获取我想要的元素,将它从队列中删除,修改它(如果我不想删除它)再次在队列中添加它。 会有用吗?
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?
原文:https://stackoverflow.com/questions/24215622