As an exercise, I am trying to implement Dijkstra's algorithm in Java using a min-priority queue. The queue has to prioritize the entries based on their distance from the source.
public static <E> void dijkstraPriority(Graph<E> g, Vertex<E> source, Vertex<E> dest) {
Map<Vertex<E>,Double> dist = new HashMap<Vertex<E>,Double>();
Map<Vertex<E>,Vertex<E>> prev = new HashMap<Vertex<E>,Vertex<E>>();
Queue<Vertex<E>> q = new PriorityQueue<Vertex<E>>(g.getVertices().size(),
new Comparator<Vertex<E>>(){
@Override
public int compare(Vertex<E> v, Vertex<E> u) {
return dist.get(v).compareTo(dist.get(u)); //error happens here
}
}
);
//The rest of the implementation
}
The error I receive on line 8 is: "Cannot refer to a non-final variable inside an inner class".
Since I have to update the distances during the algorithm, dist
cannot be final
, but this in turn prevents me from currently implementing the comparator. I looked here on SO for any similar questions, but none seems to apply to my case.
Is there any way to solve this?