【发布时间】:2016-07-10 08:04:35
【问题描述】:
课程不完整,但这是我目前所掌握的,我希望下面的测试能够通过。
public class LinkedList<T> extends AbstractSequentialList<T> {
private Node<T> head;
@Override
public boolean add(T element) {
if(head == null) {
head = new Node(element);
}
return true;
}
@Override
public ListIterator<T> listIterator(int index) {
return new LinkedListIterator<>();
}
@Override
public int size() {
return 0;
}
private class LinkedListIterator<T> implements ListIterator<T> {
private Node<T> current;
public LinkedListIterator() {
current = (Node<T>) head;
}
@Override
public boolean hasNext() {
return (current != null && current.getNext() != null)? true : false;
}
@Override
public T next() {
return null;
}
}
}
这里是 Node 类。
public class Node<T> {
private T value;
private Node next;
public Node(T value) {
this.value = value;
}
public Node(T value, Node next) {
this.value = value;
this.next = next;
}
public T getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
我的迭代器测试是这样的。
LinkedList<String> list;
ListIterator<String> iterator;
@Before
public void setUp() throws Exception {
list = new LinkedList<>();
iterator = list.listIterator();
}
@Test
public void testHasNext() throws Exception {
assertThat(iterator.hasNext(), is(false));
list.add("Hello World");
assertThat(iterator.hasNext(), is(true));
}
但是,我在第二个断言上失败了。我的问题是迭代器中的“当前”指针始终为空,即使我将它设置为封闭 LinkedList 类的头部。我怎样才能解决这个问题?谢谢。
【问题讨论】:
-
getNext() 总是返回 null 所以 (current != null && current.getNext() != null) 总是 false
-
@JEY 用 Node 类的代码更新了帖子。调试时,我实际上看到当前为空。在调用 getNext() 之前条件已经失败。
标签: java linked-list iterator