views:

68

answers:

3

I am writing a program to calculate the shortest path between two nodes. In my program I have one custom class called NodeList, which contains an ArrayList of strings (representing nodes) along with a distance. I am using Dijkstra's algorithm which involves opening up the shortest edge from each node. So, I use this loop to tabulate the possible routes from a given point:

for ( NodeList ed : edges )
    {
     if (ed.nodeList.get(0).equals(node1))
     {
      routes.add(ed);
     }
    }

This works fine, and appears to load the correct values into the variables (according to the debugger). However, when I try and set a variable to the distance of one of the nodes, I get a message "cannot find symbol variable distance". Here is the code that causes the problem:

int minDistance = routes.get(0).distance;

Is this abnormal or is there something obvious I'm missing?

+1  A: 

If the node list doesn't use generics, then the compiler can't tell which type you are get()ing, which means it assumes it's an Object, which means it has no distance member.

abyx
+1  A: 

get(0) apparently returned an object of class type which doesn't have the particular field.

There are several solutions depending on the root cause of the problem:

  • Parameterize the list if possible (e.g. NodeList<Route> instead of NodeList)
  • Cast it to the right type (e.g. int distance = ((Route) routes.get(0)).distance)
  • Make the field public (e.g. public int distance;)
  • Add a getter (e.g. public int getDistance() { return this.distance; }) and use it.
BalusC
+1  A: 

Your code doesn't make sense. You say that you have an ArrayList of Strings, but you are looking for a member called 'distance'. String doesn't have a public field called 'distance'.

Most likely you need to declare ArrayList<SomeClassOfYours> to fix this, but I can't tell what from what you posted.

bmargulies
He said the list has strings and distances, sounds like he means he already is using a class.
abyx