迭代器在LinkedList上的删除

迭代器在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++;
            }
原文地址:https://www.cnblogs.com/jiading/p/12540591.html