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.