0

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?

Luigi D.
  • 165
  • 1
  • 10
  • 3
    You're wrong that `dist` cannot be `final`. `final` does not mean "no mutation of what's being pointed to", it means the actual variable `dist` can't be changed to point to a different `Map`. – Dan Getz Jun 11 '15 at 12:46
  • 1
    `final` on variables only keeps you from reassigning the variable, what you are doing in the code provided is manipulating the value of the variable, which is allowed even with a `final` modifier. – Tobb Jun 11 '15 at 12:46
  • @Jesper how could that be a good duplicate for this question? It doesn't seem to really address this question. – Dan Getz Jun 11 '15 at 12:53
  • @DanGetz the other question addresses the same error message and has answers about why you cannot access a non-final variable in an anonymous inner class. (That doesn't mean your comment is not correct, `dist` can indeed be `final` and that will still allow modifying the content of the map). – Jesper Jun 11 '15 at 13:24
  • @Jesper this question was asked in the context of already having read questions such as the one marked as duplicate. – Dan Getz Jun 11 '15 at 13:33
  • The answers to [this other question](http://stackoverflow.com/q/19049697) seem to be more relevant to me, though the question itself is a mess and focused on class members instead of local variables. – Dan Getz Jun 11 '15 at 13:41
  • 1
    [This other question](http://stackoverflow.com/q/12727299) was asked with some of the same misconceptions as the question here. – Dan Getz Jun 11 '15 at 13:45

0 Answers0