RemoveメソッドがNullPointerExceptionを返す理由を把握しようとしています。私は、多くのシナリオに対してそれをテストしているし、それはほとんどの部分は正常に動作しているようだが、私は私の教授コードに対してそれをテストしたとき、私はNullPointerExceptionが取得:LinkedListのRemoveメソッドがNullPointerExceptionを返します。
私のドライバーに反して(これが出力されます):
List: Hamadi, Salisu, Galo, Ballo,
4
Replacing Galo with Abdullahi
List: Hamadi, Salisu, Abdullahi, Ballo,
Removing Salisu from the list
List: Hamadi, Abdullahi, Ballo,
List: 65, 21, 42,
Removing 65 from the list
List: 21, 42,
List: 1, 3,
Removing 1 from the list
List: 3,
List: 25, 3,
私は私のメンターのコードに対して(方法は下記を参照してください)私のremoveメソッドのコードをテストするまで、すべてがうまく機能:
/** Remove a node at the specified index and return its data element.
* @param index The index of the element to remove
* @return The data element removed
* @throws IndexOutOfBoundsException If index is outside the bounds of the list
*
*/
public E remove(int index)
{
// TODO: Implement this method
if (index < 0 || index >= size() || size() == 0) {
throw new IndexOutOfBoundsException("Nodes are not within the array");
}
int i = 0;
LLNode<E> currentNode = head.next;
while (i < size) {
if (i == index) {
System.out.println("Removing " + currentNode.data + " from the list");
currentNode.next.prev = currentNode.prev;
currentNode.prev.next = currentNode.next;
size--;
return currentNode.data;
}
currentNode = currentNode.next;
i++;
}
return null;
}
現在、私はノードの除去を実施している方法がにあります削除しようとしているノードを持っているtを除去されたノードの前のノードに戻し、逆もまた同様である。
可能なNullExceptionErrorsを防ぐ(そして回避する)ための削除メソッドをさらに改善するために、私ができることは非常に高く評価されます。ありがとう!
私はあなたが持っている問題は、このラインからだと思います
whileループで 'size'変数は何ですか? – SomeDude
あなたは 'head.next == null'のような条件をチェックするべきです。リストに要素が1つしかない場合です。 indexを 'size'と指定し、' next'がない場合 – SomeDude