簡體   English   中英

java-圖形中的NullPointerException

[英]java - NullPointerException in Graph

我試圖使用ArrayList的HashMap實現一個無向圖,以表示鄰接表。 但是,在初始化鄰接表時出現了空指針異常錯誤,無法識別空指針。 很抱歉這個愚蠢的問題,但是如果您能解釋為什么會發生錯誤,我將不勝感激。 謝謝!

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
    }
}

和錯誤消息:

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