0

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!

1
  • 1
    What you should do is change the code to have one statement per line. adjList[i].add(vList[j].label); should be ArrayList<String> alTmp = adjList[i]; WhateverType vTmp = vList[j]; String label = vTmp.label; alTmp.add(label); And then see where you run into the problem with the debugger Commented Apr 20, 2010 at 3:18

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Joel: Would it be correct to code this" adjList[i].contains(vList[j].label)"
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.
1

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 ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.