我想将边缘添加到Vertex类的私有链表边缘中。请帮助我解决此功能。我收到此错误:
线程“ main”中的异常java.lang.NullPointerException在 sample.Vertex.setEdges(Vertex.java:19)在 sample.Main.main(Main.java:24)
Vertex.java
package sample;
import java.util.LinkedList;
import java.util.List;
public class Vertex {
private String label;
private LinkedList<Integer> edges;
public void setLabel(String label) {
this.label = label;
}}
// public void setEdges(Edge e) {
//
// edges.add(e);
// }}
Edge.java
public class Edge {
private Vertex destination;
private double weight;
public void setWeight(double weight) {
this.weight = weight;
}
public void setDestination(Vertex destination) {
this.destination = destination;
}
public double getWeight() {
return weight;
}
public Vertex getDestination() {
return destination;
}
}
Main.java
public class Main {
// Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
public static void main(String[] args) {
// creating the graph A --1.0--> B
Vertex n = new Vertex();
n.setLabel("A");
Vertex b = new Vertex();
b.setLabel("B");
Edge e = new Edge();
e.setDestination(b);
e.setWeight(1.0);
// n.setEdges(e);
// returns the destination Node of the first Edge
double weight = e.getWeight();
System.out.print(e);
System.out.print(n);
// returns the weight of
// the first Edge
}
public static void main2(String[] args) {
launch(args);
}
}
答案 0 :(得分:0)
您收到此错误的原因是,当您创建Vertex
的新实例时,尚未初始化该Vertex
的{{1}}成员变量。让我们来看一下您的Main class:
edges
因此,在创建新的public class Main {
public static void main(String[] args) {
Vertex n = new Vertex(); // At this point, n.edges is null because it was never initialized
n.setLabel("A");
Vertex b = new Vertex();
b.setLabel("B");
Edge e = new Edge();
e.setDestination(b);
e.setWeight(1.0);
n.setEdges(e); // Now you are attempting to add an edge to a null LinkedList, hence the NullPointerException
...
}
public static void main2(String[] args) {
launch(args);
}
}
时需要初始化edges
成员变量。我们可以在构造函数中做到这一点:
Vertex