首页 > 其他 > 详细

迭代器在LinkedList上的删除

时间:2020-03-21 19:12:58      阅读:47      评论:0      收藏:0      [点我收藏+]

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

迭代器在LinkedList上的删除

原文:https://www.cnblogs.com/jiading/p/12540591.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!