views:

115

answers:

2

Am trying to solve a labyrinth by DFS, using adj List to represent the vertices and edges of the graph. In total there are 12 nodes (3 rows[A,B,C] * 4 cols[0,..,3]). My program starts by saving all the vertex labels (A0,..C3), so far so good, then checks the adjacent nodes, also no problems, if movement is possible, it proceeds to create the edge, here its where al goes wrong.

   adjList[i].add(vList[j].label);

I used the debugger and found that vList[j].label is not null it contains a correct string (ie. "B1"). The only variables which show null are in adjList[i], which leads me to believe i have implemented it wrongly. this is how i did it.

public class GraphList {
   private ArrayList<String>[] adjList;
   ...
   public GraphList(int vertexcount) {
      adjList = (ArrayList<String>[]) new ArrayList[vertexCount];
      ...
   }
   ...
   public void addEdge(int i, int j) {  
      adjList[i].add(vList[j].label);    //NULLPOINTEREXCEPTION HERE
   }
   ...
}

I will really appreaciate if anyone can point me on the right track regrading to what its going wrong... Thanks!

+3  A: 

You've created the array, but you still need to go through and create the ArrayList objects. As it's written, adjList[i] returns null because nothing has been assigned to it yet.

Joel
@Joel: Would it be correct to code this" adjList[i].contains(vList[j].label)"
Carlucho
Your addEdge method is fine. You're just not initializing your data structures correctly. You need a loop with in your constructor with `adjList[i] = new ArrayList<String>();` Alternately, you could modify addEdge to test for null and create the ArrayList if it doesn't yet exist.
Joel
+1  A: 

I see that you created the container but are you sure you populated the list with elements? Why don't you add assert((adjList[i] != null) && (adjList[j] != null)) to addEdge just to be sure either of them are not null. Run with java -ea ...

Chuk Lee