首页 > 解决方案 > 我需要在 java 中使用 hashmap 制作图表,但我的代码在 addEdge 函数中显示空指针异常

问题描述

public class graph {

private class node {
    String label;
    node(String label) {
        this.label = label;
    }
    public String getNode() {
        return label;
    }
}

private HashMap<node, ArrayList<node>> graph = new HashMap<>();

public void addNode(String label) {
    graph.putIfAbsent(new node(label), new ArrayList<>());
}

public void removeNode(String label) {
    Iterator<node> itr = graph.keySet().iterator();

    while(itr.hasNext()) {
        if(itr.next().getNode() == label) {
            itr.remove();
        }
    }
}

public void addEdge(String src, String des) {
    graph.get(src).add(new node(des));
}

public void removeEdge(String src, String des) {
    if(!graph.get(src).isEmpty()) 
        graph.get(src).forEach((n) -> remove(n, des));
}

private void remove(node n, String des) {
    if(n.getNode() == des)
        n = null;
}

public void printGraph() {
    System.out.println(graph);
}

}

我使用的是 java 版本 8。我认为问题出在 addNode 或 addEdge 函数中,但我无法弄清楚。任何帮助将不胜感激。提前致谢 :)

标签: javaarraylistgraphnullpointerexceptionhashmap

解决方案


对于将添加到的第一个边,graph它将抛出 NullpointerException,因为它没有任何以前的边要添加到

public void addEdge(String src, String des) {
    graph.get(src).add(new node(des));
}

ArrayList<node> nodes = graph.get(src); <- NPE here

在此节点对象上调用任何方法都会导致 NPE 第一次您尝试添加边,因为节点对象为null

我认为您需要决定src第一个优势是什么


推荐阅读