爲了更好地瞭解迭代器,我將自己編寫它們以嘗試獲取它們的正確功能。我有一個問題從ListIterator
以前的方法中獲得正確的行爲。正確實施List Iterator方法
例如,JavaDoc中指出:
交替調用next和以前將重複返回相同的元素。
我的Iterator
class Node<Item> {
public Item data;
public Node<Item> next;
public Node<Item> previous;
public Node() {
data = null;
next = null;
previous = null;
}
public Node(Item i, Node<Item> n, Node<Item> p) {
data = i;
next = n;
previous = p;
}
}
public ListIterator<Item> listIterator() {
return new ListIterator<Item>() {
private Node<Item> n = first;
public boolean hasNext() {
return n.next != last;
}
public Item next() {
n = n.next;
return n.data;
}
//TODO
public void remove() {
}
public boolean hasPrevious() {
return n.previous != first;
}
public Item previous() {
n = n.previous;
return n.data;
}
};
}
現在,當我測試一下,我在與previous()
方法不正確的行爲。
TEST
LinkedList<String> lst2 = new LinkedList<String>();
for (int i = 0; i < 4; i++)
lst2.add("" + "data".substring(i, i + 1));
ListIterator<String> it2 = lst2.listIterator();
System.out.println("\nTest the list iterator.\nThe test list is " + lst2 + "\n");
while (it2.hasNext()) {
System.out.println("next is " + it2.next());
System.out.println("previous is " + it2.previous());
if (removeImplemented) {
it2.remove();
System.out.println("After remove: " + lst2);
}
System.out.println("next is " + it2.next());
}
System.out.println("\nHere is how the built-in Java ArrayList class works\n");
ArrayList<String> lst3 = new ArrayList<String>();
for (int i = 0; i < 4; i++)
lst3.add("" + "data".substring(i, i + 1));
ListIterator<String> it3 = lst3.listIterator();
System.out.println("Test list iterator.\nThe test list is " + lst3 + "\n");
boolean remove = false;
while (it3.hasNext()) {
System.out.println("next is " + it3.next());
System.out.println("previous is " + it3.previous());
if (remove) {
it3.remove();
System.out.println("After remove: " + lst3);
}
System.out.println("next is " + it3.next());
}
我的結果
The test list is [d, a, t, a]
next is d
previous is null //incorrect
next is d
next is a
previous is d //incorrect
next is a
next is t
previous is a //incorrect
next is t
next is a
previous is t //incorrect
next is a
正確的結果
The test list is [d, a, t, a]
next is d
previous is d
next is d
next is a
previous is a
next is a
next is t
previous is t
next is t
next is a
previous is a
next is a
現在,我understandi ng,第二組結果是ListIterator
的正確行爲。那麼,我能做些什麼來實現這種行爲?從我讀過的內容來看,它與光標被移動到元素之前有關,而不是元素本身。我很難考慮實現這一點的方式。
的Javadoc指的是'下一個()'和'以前()Listiterator'的''方法,但它看起來像你回場'next'和以前' ''無論什麼類'節點n',因此你的不同行爲。 –
@DanielWiddis那麼現在的行爲是否正確呢? – 23k
取決於「正確」的含義。如果你試圖匹配'ListIterator'那麼顯然不是,因爲你的輸出不匹配。我沒有看到你更新n.data的位置,這是你返回的值,所以我不知道你在底層嘗試做什麼。 –