gpt4 book ai didi

java - 为什么我的迭代器中出现空指针异常?

转载 作者:搜寻专家 更新时间:2023-11-01 02:40:53 24 4
gpt4 key购买 nike

<分区>

在双向链表上调用我的迭代器时,出现空指针异常。空指针异常发生在 main 的行 assertEquals(i, (int) it.next());

     /***************************
* nested class DequeIterator
***************************/
private class DequeIterator implements Iterator<E>
{
// instance data member of ListIterator
private Node current;

// constructors for ListIterator
public DequeIterator()
{
current = first; // head in the enclosing list
}

public boolean hasNext()
{
return current != null;
}

public E next()
{
if (hasNext() == false){ throw new NoSuchElementException();}
else {
E ret = current.item;
current = current.next;
return ret;
}
}

public void addLast(E item) {

if (item.equals(null)) { throw new NullPointerException(); }

else {

Node node = new Node(item, null);
Node ptr = last;

ptr.prev.next = node;
node.next = ptr;
node.prev = ptr.prev;
ptr.prev = node;
N++;

}
}

public static void main(String[] args) {

Deque<Integer> lst = new Deque<Integer>(); // empty list


for(int i = 1; i <= 5; i++) {
lst.addLast(i);
}
assertEquals(5, lst.size());
Iterator<Integer> it = lst.iterator();
int i = 1;
while(it.hasNext()) {
assertEquals(i, (int) it.next());
i++;
}
assertEquals(6, i);
assertEquals(5, lst.size());
}

谁能告诉我为什么此时出现空指针异常?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com