简体   繁体   English

java-图形中的NullPointerException

[英]java - NullPointerException in Graph

I was trying to implement an undirected graph using a HashMap of ArrayList to represent the adjacency list. 我试图使用ArrayList的HashMap实现一个无向图,以表示邻接表。 However, I got the null pointer exception error when I initialize the adjacency list, in which I was unable to identify the null pointer. 但是,在初始化邻接表时出现了空指针异常错误,无法识别空指针。 Sorry for the stupid question but I'd appreciate it if you could explain why the error occurs. 很抱歉这个愚蠢的问题,但是如果您能解释为什么会发生错误,我将不胜感激。 Thanks! 谢谢!

import java.util.HashMap;
import java.util.ArrayList;

public class UDGraph {      //ajacency list implementation
    private final int V;
    private int E;
    private HashMap<Integer, ArrayList<Integer>> adj;

    public UDGraph(int V) {
        this.V = V;
        this.E = 0;
        for (int v = 0; v < V; v++) {
            Integer vertice = new Integer(v);
            ArrayList<Integer> list = new ArrayList<Integer>();
            adj.put(vertice, list);        //LINE 15
        }
    }

    public static void main(String[] args) {
        UDGraph graph = new UDGraph(5);    //LINE 20
    }
}

And the error message: 和错误消息:

Exception in thread "main" java.lang.NullPointerException
at UDGraph.<init>(UDGraph.java:15)
at UDGraph.main(UDGraph.java:20)

您只需要在您的哈希表上调用new HashMap<Integer, ArrayList<Integer>> adj = new HashMap<>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM