我尝试使用txt文件构建一个呼吸优先搜索关系(BFS)。当BFS大小很小(例如7个节点)时,它可以很好地工作,但是当BFS大小很大时(例如,20000个节点),会出现NullPointerException。我已经阅读了一些关于NullPointerException的帖子,但我仍然不知道如何解决它。
异常消息:
Exception in thread "main" java.lang.NullPointerException
at GraphAdjacentList.setEdge(GraphAdjacentList.java:16)
at GraphAdjacentListDemo.main(GraphAdjacentDemo.java:52)
有7个节点,然后每一行显示两个节点的关系。 txt文件的格式:
7
1 2
1 3
1 4
4 5
4 6
5 7
我的代码:
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){}
}
}