ArrayList<字符串>空指针异常字符串>
我试图通过 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已经创建了数组,但仍然需要检查并创建 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.我看到您创建了容器,但您确定已使用元素填充列表吗?
为什么不将
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))
toaddEdge
just to be sure either of them are notnull
. Run withjava -ea ...