我一直在 stackoverflow 上搜索 1000 个 NullPointerException 帖子,但我一生都无法弄清楚为什么会发生这种情况;除了显而易见的(它是空的)。有人可以帮助我了解导致我遇到此运行时错误的 Generic Singly LinkedList 是什么我不了解。
这是我的代码:
import java.io.*;
import java.util.*;
public class GList<T> {
private GNode<T> head;
private GNode<T> cursor;
private static class GNode<E>{
private E data; //NULLPOINTEREXCEPTION
private GNode<E> next;
public GNode(E data, GNode<E> next) {
this.data = data;
this.next = next;
}
}
public static class InnerList<E> {
private String name;
private GList<Integer> inner = new GList<Integer>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GList<Integer> getInner() {
return inner;
}
public void setInner(GList<Integer> inner) {
this.inner = inner;
}
}
public boolean hasNext(T cursor) {
/*
* returns whether or not the node pointed to by 'cursor' is
* followed by another node. If 'head' IS null, returns False
*/
if (cursor != null)
{
return true;
}
else
{
return false;
}
}
public void insertFirst(T t) {
/*
* puts a new node containing t as a new first element of the list
* and makes cursor point to this node
*/
if (hasNext(t) == false){
head = new GNode<T>(t, head);
head.next.data = t;
cursor.next = head;
}
else{
System.out.println("List is not null.");
}
}
public static void main(String[] args){
GList<InnerList> list = new GList<InnerList>();
String ln = "hello";
list.cursor.next.data.setName(ln); //NULLPOINTEREXCEPTION
/*Exception in thread "main" java.lang.NullPointerException
*at GList$GNode.access$0(GList.java:10)
*at GList.main(GList.java:67)
*/
}
}
这是家庭作业,所以解释将是最有帮助的,因为我确信我将在接下来的几个月里处理 LinkedList。