私は何千もの NullPointerException の投稿をスタックオーバーフローで精査してきましたが、これがなぜ起こっているのか一生理解できません。明らかなことは別として(それがnullであること)。この実行時エラーが発生する原因となっている 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 を扱うことになると確信しているため、説明が最も役立ちます。