方法调用可能会产生nullpointerexception

时间:2017-04-01 21:21:45

标签: java nullpointerexception

我尝试使用邻接列表来实现Graph,但是当我尝试在列表中添加新对时,它会给我一个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();
        }
    }
}

1 个答案:

答案 0 :(得分:-1)

new Graph()放在第二个构造函数中并不会初始化它。您只需声明默认图表,不要将其存储在任何位置。现在,如果你使用特殊功能this,你就会得到你想要的东西。

public Graph(String filePath) {
    this();
    ...
相关问题