June 20, 2013

Access an internally used list

Pulz’s Question:

I’m coding the Dijkstra algorithm in Java. My first method

public void populateDijkstraFrom(Node startNode)

creates a Linked List of nodes with its respective distances and predecessors. My second method

public List<Node> getShortestPath(Node startNode, Node targetNode)

is supposed to create a list of nodes with the shortest path from the startNode to the targetNode using the list of nodes from my populateDijkstraFrom method.

However, I don’t know how to access the list of nodes from my Dijkstra method in the getShortestPath method. I could change the return type from void to LinkedList but I was told that it works using void.

How do I do it?


There are basically two ways of solving this.

Easiest one would be return the list of nodes on your method

public List<Node> populateDijkstraFrom(Node startNode) {
       // ^ Configure to return list instead of void

    // ......
    return nodeList;

public List<Node> getShortestPath(Node startNode, Node targetNode) {
    List<Node> pdList = populateDijkstraFrom(startNode);
    // ^ --- Get the list by simply passing the same parameter to the method

Another is stated by Gian

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!