I am trying to implement a graph in Java using an arrayList
of arrayList
.
I keep getting a NullPointerException
whenever the addEdge
function is called. I cannot seem to figure out why.
Here is my code:
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));
}
}
Please kindly advise.
In your Graph
constructor, you're not initializing the static
member adjList
, but rather are defining a local one with the same name. Also, there's no need adjList
to be static
, because it will be shared among all instances of Graph
.
Adjust it to:
private ArrayList<ArrayList<Integer>> adjList;
public Graph(int vertices){
adjList = new ArrayList<ArrayList<Integer>>();
...
}
You should remove static
in adjList
field declaration.
This modifier makes adjList
a static instance which refers to null
. And in the constructor you instantiate value for another adjList
that is local for your constructor (and is subject to be gathered by GC after the constructor is called). It is two completely different variables with the same name
change your constructor so that you are not declaring a local adjList variable
public Graph(int vertices){
adjList = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < vertices; i++){
adjList.add(new ArrayList<Integer>());
}
}
Also make this adjList variable non static since you want the adjList to be unique to each graph and not shared across all of them
private ArrayList<ArrayList<Integer>> adjList;
In the Graph constructor, you declare an adjList variable, which is in conflict with your static class. You should replace
public Graph(int vertices){
ArrayList<ArrayList<Integer>> adjList = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < vertices; i++){
adjList.add(new ArrayList<Integer>());
}
}
by
public Graph(int vertices){
adjList = new ArrayList<ArrayList<Integer>>();
for(int i = 0; i < vertices; i++){
adjList.add(new ArrayList<Integer>());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.