我正在尝试创建从文本文件读取的无向图.但是我一直收到NullPointerException.这是我的Graph类:
Graph.java:
package testalgo;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Graph
{
ArrayList<Integer> vertices = new ArrayList<Integer>();
HashMap<Integer, LinkedList<Integer>> adj;
static Scanner sc;
public Graph(ArrayList<Integer> verts ){
adj =new HashMap<Integer, LinkedList<Integer>>();
}
public static void main(String[] args) {
try{
sc = new Scanner(new File("graph1.txt"));
}
catch(Exception e){
System.out.println(e);
}
while(sc.hasNext()){
int a = Integer.parseInt(sc.next());
int b = Integer.parseInt(sc.next());
Graph g = new Graph(new ArrayList<Integer>());
g.addVertex(a);
g.addeEgde(a, b); // this is line 46
g.addeEgde(b, a);
}
sc.close();
}
public void addVertex(int v){
for (int i = 1; i < vertices.size(); ++i) {
adj.put(i, new LinkedList<Integer>());}
}
public void addeEgde(int v1, int v2) {
adj.get(v1).add(v2); // this is line 68
}
public List<Integer> getNeighbors(int v) {
return adj.get(v);
}
}
这是我收到的错误消息:
Exception in thread "main" java.lang.NullPointerException
at testalgo.Graph.addeEgde(Graph.java:68)
at testalgo.Graph.main(Graph.java:46)
谢谢你的帮助!
解决方法:
在您的代码中,没有看到您使用v作为键填充adj映射的地方.因此adj.get(v1)将返回null.您只声明了adj;您还需要填充它.
我所看到的是:
for (int i = 1; i < vertices.size(); ++i) {
adj.put(i, new LinkedList<Integer>());
}
由于开始时顶点是空的,因此您不会在地图中插入任何内容.
你的意思是:
adj.put(v, new LinkedList<Integer>());
代替?
回应您的评论:您需要在邻接表中为b添加另一个条目:
g.addVertex(a);
g.addVertex(b); // <--- you need this as well
g.addeEgde(a, b);
g.addeEgde(b, a); // <--- otherwise you'll get a NPE here