0

私は何千もの 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 を扱うことになると確信しているため、説明が最も役立ちます。

4

2 に答える 2

5

実装を指定していないデフォルトのコンストラクターを使用しているため

GList<InnerList> list = new GList<InnerList>();

どのフィールドも初期化されていないため、

list.cursor == null

Java はここで実行を停止しますが、他のフィールドも null です。時間をかけてコードを見直し、関連するすべてのフィールドを初期化してください。

実際には、リストにアイテムを追加していないため、リスト内の何かにアクセスしようとすべきではありません。そのheadcursorは null です。

于 2013-02-19T20:43:23.243 に答える
1

この行list.cursor.next.data.setName(ln);では、初期化されていないオブジェクトのプロパティを参照しようとしています。

カーソル、次、およびデータを宣言する場所では、値を設定しません。メインメソッドでは、ヘッドまたはカーソルの値を設定していないため、それらはまだ null です。次に、それらを参照して NPE を取得しようとします。

于 2013-02-19T20:44:12.603 に答える