每当尝试从节点创建简单边时,都会出现错误。基本上,我创建了两个自己的类,分别称为Node和Edge。
Node类如下:
public class Node {
public String ident;
public int numLinks;
public Edge[] neighbours;
public Node (String ident) {
this.ident = ident;
}
public void setNeighbour (Node start, Node end, int cost, int portNum) {
}
}
我的Edge类如下:
public class Edge {
Node start;
Node end;
int cost;
int portNum;
public Edge (Node a, Node b, int cost, int portNum) {
this.start = a;
this.end = b;
this.cost = cost;
this.portNum = portNum;
}
}
在我的主类中,我创建两个节点,即开始和结束节点。我从一个文本文件中读取了成本和端口号(这两个节点都在其上监听的端口号),并将其保存到名为“ linkCostList”和“ portNumList”的数组列表中。
现在,由于每个起始节点可以具有多个边缘(我基本上是在创建图形),所以我通过以下方式调用setNeighbour()方法:
for (int i = 0; i < startNode.numLinks; i++) {
nextNode = new Node (String name of node I read from text file)
startNode.setNeighbour (startNode, nextNode, linkCostList.get(i), portNumList.get(i));
}
我的setNeighbour方法如下:
public void setNeighbour (Node start, Node end, int cost, int portNum) {
for (int i = 0; i < start.numLinks; i++) {
neighbours[i] = new Edge (start, end, cost, portNum);
}
}
每次编译时,都会出现以下错误:
Exception in thread "main" java.lang.NullPointerException
at Node.setNeighbour(Node.java: *line number*)
at Start.startlsr(Start.java: *line number*)
at graph.main(lsr.java: *line number*)
}
我知道这是一个空指针异常,因此,在该循环中的某个地方,我必须做错了什么。谁能帮我弄清楚吗?
您是否在您的neighbours
类中初始化了Node
?看起来异常是访问空数组(neighbours[i]
)。
还看起来neighbours
数组会动态增长/缩小吗?在这种情况下,考虑使用ArrayList而不是使用数组,这样就不必自己增加neighbours
。
进一步@Alvin的答案(您尚未初始化邻居,也不允许扩展),请尝试以下操作:
public List<Edge> neighbours = new ArrayList<Edge>();
也利用java的“ foreach”:
for (Edge edge : start.neighbours) {
// .. some code
}
考虑将“邻居”重命名为“边缘”,因为它们就是节点的边缘。
最后,看来您的逻辑中有错误。看来太复杂了。您可能正在尝试保留邻居的邻居的引用。考虑在需要时简单地查找东西。