迭代器在LinkedList上的刪除
源碼如下:
public void remove() {
this.checkForComodification();
if (this.lastReturned == null) {
throw new IllegalStateException();
} else {
LinkedList.Node<E> lastNext = this.lastReturned.next;
LinkedList.this.unlink(this.lastReturned);
if (this.next == this.lastReturned) {
this.next = lastNext;
} else {
--this.nextIndex;
}
this.lastReturned = null;
++this.expectedModCount;
}
}
從源碼中就可以看出來,刪除的節點不是next節點,而是lastReturned,所以我們在使用的時候要注意,因為一開始next指向的才是第一個元素,lastReturned里是null,所以如果我們想要刪除下一個元素,想要先用iterator.next()將該元素讀到lastReturned中,再調用iterator.remove,否則就會錯刪為前一個節點。
例如:
while(iterator.hasNext()){
if(curl%loop!=0){
//注意這里需要先用next再刪
iterator.next();
iterator.remove();
}else{
iterator.next();
}
curl++;
}