方法调用可能会产生nullpointerexception
问题描述:
我想实现使用邻接列表的Graph,但是当我尝试向列表中添加新对时,它给了我一个NullPointerException
。有谁知道为什么会发生,以及如何解决它?方法调用可能会产生nullpointerexception
在此先感谢。
我Graph.java
是这样的:
import javafx.util.Pair;
import java.util.*;
public class Graph{
private final HashMap<String, List<Pair<String, Integer>>> adj;
public Graph(String filePath) {
adj = new HashMap<>();
addEdge("a", "b", 30);
}
public void addEdge(String start, String end, int weight) {
adj.get(start).add(new Pair<>(end, weight));
}
}
我Main.java
是这样的:
public class Main {
public static void main(String[] args) {
Graph gr;
try {
gr = new Graph("test.txt");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
答
只是把new Graph()
在你的第二个构造函数不初始化。您只需声明一个默认图形,不要将其存储在任何地方。现在,如果你使用特殊功能this
,你会得到你想要的。
public Graph(String filePath) {
this();
...
+0
你说得对,但这不是导致这个问题的原因。我试图使用'this()',但它不起作用。 – Fingal
+0
你*不*对*。在OP的代码中,没有零参数构造函数。因此,添加'this();'不会编译。 –
芬戈尔 - 你没有在你的问题中包括堆栈跟踪。由于在没有堆栈跟踪的情况下找到NPE的原因很大程度上是猜测,所以您的问题被标记为通用问答的副本,其答案解释了如何为自己调试和修复NPE。您对问题的后续修订无助于此。 –
但是这里有一个提示。当'adj'是一个新创建的(因此是空的)'HashMap'时,'adj.get(start)'会返回什么? –