クラスは完全ではありませんが、これまで私が持っていたことがあります。Java - カスタムイテレータがカスタムリンクリストの先頭を追跡できない
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));
}
しかし、私は2番目のアサーションには失敗しています。私の問題は、イテレータの "現在の"ポインタが、それを囲んでいるLinkedListクラスの先頭に設定していても、常にnullであることです。これをどうすれば解決できますか?ありがとう。
getNext()は常にnullを返します。現在の!= null && current.getNext()!= null)は常にfalseです。 – JEY
@JEY Nodeクラスのコードでポストを更新しました。デバッグするとき、私は実際には現在のnullを参照してください。 getNext()が呼び出される前に条件が既に失敗しました。 – user2017502