Java图形实现:nullpointerexception



我正试图使用arrayListarrayList在Java中实现一个图。

每当调用addEdge函数时,我总是得到一个NullPointerException。我似乎不明白为什么。

这是我的代码:

import java.util.ArrayList;
public class Graph {
    private static ArrayList<ArrayList<Integer>> adjList;
    public Graph(int vertices){
        ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>();
        for(int i = 0; i < vertices; i++){
            adjList.add(new ArrayList<Integer>());
        }
    }
    public void addEdge(int source, int destination){
        adjList.get(source).add(destination);
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Graph g = new Graph(4);
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 2);
        g.addEdge(2, 0);
        g.addEdge(2, 3);
        g.addEdge(3, 3);
        System.out.println("Neighbors of vertex 0: " + adjList.get(0));
        System.out.println("Neighbors of vertex 2: " + adjList.get(2));
    }
}

请告知。

Graph构造函数中,您不是在初始化static成员adjList,而是在定义一个具有相同名称的本地成员。此外,adjList不需要是static,因为它将在Graph的所有实例之间共享。

将其调整为:

private ArrayList<ArrayList<Integer>> adjList;
public Graph(int vertices){
    adjList = new ArrayList<ArrayList<Integer>>();
    ...
}

更改构造函数,这样就不会声明本地adjList变量

public Graph(int vertices){
    adjList = new ArrayList<ArrayList<Integer>>();
    for(int i = 0; i < vertices; i++){
        adjList.add(new ArrayList<Integer>());
    }
}

还要使这个adjList变量非静态,因为你希望adjList对每个图都是唯一的,而不是在所有图之间共享

private ArrayList<ArrayList<Integer>> adjList;

您应该删除adjList字段声明中的static

此修饰符使adjList成为引用null的静态实例。在构造函数中,您实例化另一个adjList的值,该值是构造函数的本地值(并且在调用构造函数后由GC收集)。它是两个完全不同的变量,名称相同

在Graph构造函数中,您声明了一个adjList变量,该变量与您的静态类冲突。你应该更换

public Graph(int vertices){
        ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>();
        for(int i = 0; i < vertices; i++){
            adjList.add(new ArrayList<Integer>());
        }
    }

通过

public Graph(int vertices){
        adjList = new ArrayList<ArrayList<Integer>>();
        for(int i = 0; i < vertices; i++){
            adjList.add(new ArrayList<Integer>());
        }
    }

相关内容

最新更新