ArrayList<字符串>空指针异常

发布于 2024-08-30 04:55:57 字数 761 浏览 3 评论 0原文

我试图通过 DFS 解决迷宫问题,使用 adj List 来表示图的顶点和边。总共有 12 个节点(3 行[A,B,C] * 4 列[0,..,3])。我的程序首先保存所有顶点标签(A0,..C3),到目前为止一切顺利,然后检查相邻节点,也没有问题,如果可以移动,则继续创建边,这里是所有出错的地方。

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

我使用调试器,发现 vList[j].label 不为空,它包含正确的字符串(即“B1”)。唯一显示 null 的变量位于 adjList[i] 中,这让我相信我错误地实现了它。我就是这样做的。

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

如果有人能指出我在正确的轨道上重新定位出了什么问题,我将非常感激......谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

习惯成性 2024-09-06 04:55:57

您已经创建了数组,但仍然需要检查并创建 ArrayList 对象。正如所写,adjList[i] 返回 null,因为尚未为其分配任何内容。

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.

留一抹残留的笑 2024-09-06 04:55:57

我看到您创建了容器,但您确定已使用元素填充列表吗?
为什么不将 assert((adjList[i] != null) && (adjList[j] != null)) 添加到 addEdge 只是为了确保它们都不为 null。使用 java -ea ... 运行

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文