我刚开始处理图表,我正在尝试用城市建立一个邻接列表。这两个城市被发送到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);
}
}
}Main:
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");
}发布于 2014-03-26 02:37:44
在您编写的代码行中
Vertex [] aList= new Vertex [50];这只会为您分配足够的空间来容纳多达50个Vertex项。然而,这并不意味着数组在分配之后就会被填充。因此,您基本上有能力存储50个Vertex项目。
在您的方法addRelation中,它检查的是!aList[i].city.equals(from),但是aList数组没有任何实际的Vertex对象,所以当您试图从aList[i]查询city字段时,实际上是在查询空对象,因此出现了空指针异常。
有两种解决办法。
Vertex对象填充数组。虚拟方法将要求您使用构造函数参数的空字符串/空参数初始化对象,或者您可以实现默认构造函数,只需说new Vertex(),然后在代码逻辑中自定义Vertex对象的city和next字段。
https://stackoverflow.com/questions/22650310
复制相似问题