gpt4 book ai didi

java - 使用javapriorityQueue删除方法

转载 作者:行者123 更新时间:2023-11-30 06:08:19 26 4
gpt4 key购买 nike

我正在寻找带有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() 方法的返回值是 bool。如果队列因调用而改变,则返回“true”,否则返回“false”,但也不异常(exception)!

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

关于java - 使用javapriorityQueue删除方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50813265/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com