[英]Java Iterator Doubly Linked list
Hi I'm very new to Java and trying to create a Deque
class by implementing a doubly linked-list format. 嗨,我对Java很新,并尝试通过实现双链表格式来创建
Deque
类。 When I run the code(DequeApp), I get a NullPointerException
refer back to my Iterator.next(Deque.java:44). 当我运行代码(DequeApp)时,我得到一个
NullPointerException
请回到我的Iterator.next(Deque.java:44)。
Error messages: **Exception in thread "main" java.lang.NullPointerException
at dlist.Deque$DoubleListIterator.next(Deque.java:44)
public E next() {
if (!hasNext()) {throw new NoSuchElementException();}
else{
E temp = current.item;
current = current.next;
return temp;}
}
I have made two changes. 我做了两处改动。
Start current from head, not head.next. 从头开始电流,而不是head.next。
private class DoubleListIterator implements Iterator<E> { // instance variable private Node current = head; private int index = 0; public boolean hasNext() { return index < N; } public E next() { if (!hasNext()) { throw new NoSuchElementException(); } else { index++; E temp = current.item; current = current.next; return temp; } } public void remove() { throw new UnsupportedOperationException(); } }
You forgot to increment your index
counter in the DoubleListIterator
. 您忘记在
DoubleListIterator
递增index
计数器。 You write: 你写:
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
} else {
E temp = current.item;
current = current.next;
return temp;
}
}
And you should have written: 你应该写:
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
} else {
index ++; // <---- without this, hasNext() always returns true
E temp = current.item;
current = current.next;
return temp;
}
}
Note also that I have changed the indenting format to that of Oracle's guidelines. 另请注意,我已将缩进格式更改为Oracle指南的格式。
A second error is that you initialize your Iterator as follows: 第二个错误是您按如下方式初始化Iterator:
private Node current=head.next;
However, this makes it impossible to retrieve head
(as you are already pointing to its next
node). 但是,这使得无法检索
head
(因为您已经指向其next
节点)。 And it makes you index counter off-by-one. 它使你逐个索引计数器。 Corrected code:
更正代码:
private Node current=head;
Another option to using index variable is 使用索引变量的另一个选择是
Maybe you could try "current.next != null" within hasNext. 也许你可以在hasNext中尝试“current.next!= null”。
But if it is already working with index no issues then. 但如果它已经与索引一起工作没有问题那么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.