此代码:
package Datastructures;
public class ChainNode {
Object element;
ChainNode next;
public ChainNode() {
}
public ChainNode(Object element) {
this.element = element;
}
public ChainNode(Object element, ChainNode next) {
this.element = element;
this.next = next;
}
public static void main(String args[]) {
ChainNode firstNode = new ChainNode("a");
ChainNode newNode = new ChainNode("b", firstNode.next);
ChainNode newNode2 = new ChainNode("c", firstNode.next.next);
System.out.println(firstNode.element);
System.out.println(newNode.element);
}
}
堆栈追踪:
Exception in thread "main" java.lang.NullPointerException
at Datastructures.ChainNode.main(ChainNode.java:24)
答案 0 :(得分:0)
这是因为您构建了后续ChainNode
个对象,并为前一个对象的null
字段提供了next
引用,而您应该引用之前的public static void main(String args[]) {
ChainNode firstNode = new ChainNode("a");
ChainNode newNode = new ChainNode("b", firstNode);
ChainNode newNode2 = new ChainNode("c", newNode);
System.out.println(firstNode.element);
System.out.println(newNode.element);
}
字段对象本身。试试这个:
{{1}}