在學習LinkedList源碼時,發現對它的內部迭代器ListItr的實現有幾個函數費了一番腦筋,記錄下來供以後複習使用。這幾個函數是next()、previous()以及remove()。
先把它們的源碼貼上來:
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public E previous() {
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
throw new IllegalStateException();
Node<E> lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
expectedModCount++;
}
next比較直觀,next後移一位,lastReturned位於next之前。而previous在執行後,lastReturned與next相等了。這樣就導致在remove操作中刪除掉lastReturned結點後,需要增加一次判斷。若上一次操作是previous(),則此時刪除lastReturned後,next也會“懸空”,需要將其指向lastNext。若上一次操作是next(),則刪除lastReturned時next結點不會受到影響。