java - 我需要在 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 函数中,但我无法弄清楚。任何帮助将不胜感激。提前致谢 :)
解决方案
对于将添加到的第一个边,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
第一个优势是什么
推荐阅读
- computer-vision - 逐像素回归。如何从 Nx1xHxW 到 Nx3xHxW?
- python - 未解决的参考“graphene_django”
- reactjs - 反应表多选过滤器不过滤数据
- node.js - Access-Control-Allow-Origin 阻止了我的帖子,但我允许了
- python - 你能在 python 中“嵌套”模块吗?
- python - ValueError:无法将字符串转换为浮点数:'what'(Sklearn),如何使用标签编码器?
- nginx - 在 nginx 重写中删除参数
- vue.js - Vue js for loop - 当新元素添加到dom时触发js
- c++ - C ++分配并签入一行?
- typescript - 是否可以从 Testcafe 中已定义的 Selector 中获取字符串定位器?