迭代器在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++;
            }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM