2

私は本当にイライラする問題を抱えています:

イテレータを実行しようとしていますが、hasNext クラスで java.lang.NullPointerException が発生し続けます。

どこで null 値を使用しようとしているかはよくわかりません。私はそれが現在と関係があると仮定しています。current が null かどうかを確認する if ステートメントを追加しました。しかし、それは予期しない値を返します。

助けていただければ幸いです。

以下のコード:

private class Iterator implements Iterator
{
    private Link<T> current;

    public boolean hasNext () { 
        if(current.next == null)
            return false;
        return true;
    }

    public T next() throws OutOfBounds
    {
        if (this.hasNext())
        {
            T element = current.element;
            current = current.next;
            return element;
        }
        else 
            throw new OutOfBounds("No next element to call");
    }
}

private class Link<T> 
{
    private T       element;
    private int     priority;
    private Link<T> next;

    public Link(T t, int p, Link<T> n) 
    {
        this.element = t;
        this.priority = p;
        this.next = n;
    }
}

}

4

3 に答える 3

5

おそらく初期化していないcurrentため、メソッドのチェックは、チェックする前にhasNext比較する必要がありますnullcurrnetcurrent.next

チェックを変更する

if(current.next == null)

に:

if(current == null || current.next == null)

または、メソッドを次のように変更します。

public boolean hasNext () { 
   return (current != null && current.next != null);
}
于 2013-05-17T07:14:25.847 に答える