使用 java 优先级队列删除方法



我正在寻找带有java的dijkstra算法。

下面的代码工作正常。

public static void computePaths(Vertex source, Subway p, int broken)
{
//set the source vertex distance to 0 (as distance source->source=0)
source.minDistance=0;
//init queue , add source to keep track of nodes visited (cloud)
PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
vertexQueue.add(source);
//keep track of total vertices tracked so as not to go in circles
List<Integer> l=new LinkedList<Integer>();
// while the cloud is not empty
while (!vertexQueue.isEmpty()) {
// take the head as u and...
Vertex u = vertexQueue.poll();
//(add position of u to the tracking list)
l.add(new Integer(u.pos));

// ...Visit each edge exiting u
Iterator<Edge> it=(p.subwayNetwork.getEdges(u.pos)).iterator();
while (it.hasNext())
{
Edge e= it.next();
Vertex v = e.dest;
Double weight = e.weight;
// calculate the distance from u to the node v
Double distanceThroughU = u.minDistance + weight;
// if the distance is less then the min. distance, and not already visited, and  neither
// the vertice and edge are broken
if (distanceThroughU < v.minDistance && !l.contains(v.pos) && v.pos!=broken && !e.broken) {
//remove the node form the queue and update the distance and prev. value
vertexQueue.remove(v);
//update the distance
v.minDistance=distanceThroughU;
//update the path visited till now 
v.previous = u;
//reenter the node with the new distance
vertexQueue.add(v);
}
}
}
}

为什么该vertexQueue.remove(v);没有错误?

由于我们初始化了队列,因此我们添加了一些东西然后轮询。

所以队列可能是空的。

我以为删除操作发生NoSuchElementException错误。

但它运行正常。

和建议将不胜感激

remove((-方法将布尔值作为其返回值。 如果队列因调用而更改,则返回"true",否则,它将返回"false",但没有例外!

来源: https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#remove(java.lang.Object(

最新更新