简体   繁体   中英

ArrayList<String> NullPointerException

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM