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