我刚刚开始使用图表,我正在尝试使用城市构建邻接列表。这两个城市被发送到 addRelation 方法中。我试图说,如果已经没有与第一个或最后一个字符串匹配的顶点,请使用尚不存在的字符串创建一个新顶点。现在我得到的只是带有 * 的行的空指针异常。有人对我做错了什么或我应该做什么有任何想法吗?
public class AdjList {
public class Node{
int num;
Node next;
Node(int num, Node next){
this.num=num;
this.next=next;
}
}
public class Vertex{
String city;
Node list;
Vertex(String city, Node next){
this.city=city;
this.list=next;
}
}
Vertex [] aList= new Vertex [50];
void addRelation(String from, String to) {
for(int i=0; i<aList.length; i++){
****if(!aList[i].city.equals(from)){****
aList[i]=new Vertex(from, null);
}
if(aList[i].city.equals(from)){
aList[i]=new Vertex(from, null);
}
}
}
主要:
public static void main(String args[]) {
AdjList g = new AdjList ();
g.addRelation("Atlanta", "Chattanooga");
g.addRelation("Chattanooga", "Nashville");
g.addRelation("Chattanooga", "Knoxville");
g.addRelation("Atlanta", "Birmingham");
g.addRelation("Greenville", "Knoxville");
}
最佳答案
在您编写的代码行
Vertex [] aList= new Vertex [50];
这只是为您分配了足够的空间,可以潜在容纳最多 50 个Vertex
项目。但这并不意味着数组将在分配后立即填充它们。所以你基本上有容量来存储 50 个顶点
项。
在您的方法addRelation
中,它正在检查!aList[i].city.equals(from)
,但是aList
数组确实没有任何实际的 Vertex
对象,因此当您尝试从 aList[i]
查询 city
字段时,您实际上是在尝试查询null 对象,因此出现空指针异常。
对此有两种解决方法。
- 在继续循环之前检查 null(正如您在评论中建议的那样)
- 在调用任何方法之前,使用虚拟
Vertex
对象填充数组。
虚拟方法要求您使用构造函数参数的空字符串/空参数来初始化对象,或者您可以实现默认构造函数并只需说new Vertex()
,然后自定义逻辑中
和 Vertex
对象的 code>citynext
字段。
关于java - 邻接表添加关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22650310/