【发布时间】:2016-01-30 23:24:20
【问题描述】:
在双向链表上调用我的迭代器时,我得到一个空指针异常。空指针异常发生在 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());
}
谁能告诉我为什么此时我得到一个空指针异常?
【问题讨论】:
-
您将空值转换为
int