gpt4 book ai didi

Java图实现: nullpointerexception

转载 作者:行者123 更新时间:2023-11-30 02:59:40 25 4
gpt4 key购买 nike

我正在尝试使用 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 不需要是静态,因为它将在 Graph 的所有实例之间共享。

调整为:

private ArrayList<ArrayList<Integer>> adjList;

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

关于Java图实现: nullpointerexception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36280163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com