I try to construct a breath first search relationship(BFS) by using a txt file. It works perfectly when the BFS size is small(eg. 7nodes), but NullPointerException appears when the BFS size is big(eg. 20000nodes). I've already read some posts about NullPointerException, but I still have no idea on how to solve it.
The exception message:
Exception in thread "main" java.lang.NullPointerException
at GraphAdjacentList.setEdge(GraphAdjacentList.java:16)
at GraphAdjacentListDemo.main(GraphAdjacentDemo.java:52)
There are 7 nodes, then each line shows the relationship of two nodes. The format of the txt file:
7
1 2
1 3
1 4
4 5
4 6
5 7
My code:
import java.util.*;
import java.io.*;
public class GraphAdjacentListDemo{
/* to build an adjacentList */
final private Map<Integer, List<Integer>> Adjacent_List;
public GraphAdjacentListDemo(int numberOfVertices){
Adjacent_List = new HashMap<Integer,List<Integer>>();
for(int i=1;i<=numberOfVertices;i++){
Adjacent_List.put(i,new LinkedList<Integer>());
}
}
public void setEdge(int source,int destination){
List<Integer> sList = Adjacent_List.get(source);
sList.add(destination);
List<Integer> dList = Adjacent_List.get(destination);
dList.add(source);
}
public List<Integer> getEdge(int source){
return Adjacent_List.get(source);
}
public static void main(String args[]) throws Exception{
/* to import a node source file */
File f = new File("/Users/apple/Desktop/Graph_Sample.txt");
List<Integer> source = new ArrayList<Integer>();
int count=0;
Scanner sc = new Scanner(f);
while(sc.hasNextInt()){
int i=0;
i = sc.nextInt();
source.add(i);
count++;
}
sc.close();
/* to store nodes into source_array and destination_array */
int time=(count-1)/2;
List<Integer> sourceList = new ArrayList<Integer>();
List<Integer> destinationList = new ArrayList<Integer>();
for(int i=1;i<=time;i++){
sourceList.add(source.get(1+2*(i-1)));
destinationList.add(source.get(2+2*(i-1)));
}
GraphAdjacentList adjacentList = new GraphAdjacentList(source.get(0));
for(int i=0;i<sourceList.size();i++){
adjacentList.setEdge(sourceList.get(i),destinationList.get(i));
}
System.out.println("The graph is:\n");
try{
for(int i=1;i<=source.get(0);i++){
System.out.print(i+"-->");
List<Integer> edgeList = adjacentList.getEdge(i);
for(int j=1;;j++){
if(j != edgeList.size()){
System.out.print(edgeList.get(j-1)+"-->");
}else{
System.out.print(edgeList.get(j-1));
break;
}
}
System.out.println();
}
}catch(InputMismatchException inputMismatch){}
}
}