最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java中LinkedList使用迭代器優(yōu)化移除批量元素原理

 更新時(shí)間:2021年10月31日 15:21:09   作者:wsdfym  
本文主要介紹了java中LinkedList使用迭代器優(yōu)化移除批量元素原理,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文主要介紹了java中LinkedList使用迭代器優(yōu)化移除批量元素原理,分享給大家,具體如下:

public interface Iterator<E> {
    /**
     *是否還有下一個(gè)元素
     */
    boolean hasNext();
    /**
     *下一個(gè)元素
     */
    E next();
    /**
     * 從集合中刪除最后一個(gè)返回的元素
     */
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
    /**
     * 傳入一個(gè)Consumer對(duì)剩余的每個(gè)元素執(zhí)行指定的操作,直到所有元素已處理或操作引發(fā)異常
     */
    default void forEachRemaining(Consumer<? super E> action) {
        //requireNonNull 靜態(tài)方法將會(huì)在參數(shù)為null時(shí)主動(dòng)拋出NullPointerException 異常。
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}
public interface ListIterator<E> extends Iterator<E> {
    
    /**
     * 是否有后繼
     */
    boolean hasNext();
    /**
     * 后繼節(jié)點(diǎn)
     */
    E next();

    /**
     * 是否有前驅(qū)
     */
    boolean hasPrevious();

    /**
     * 前驅(qū)節(jié)點(diǎn)
     */
    E previous();

    /**
     * 下一個(gè)節(jié)點(diǎn)的下標(biāo)
     */
    int nextIndex();

    /**
     * 前驅(qū)節(jié)點(diǎn)的下標(biāo)
     */
    int previousIndex();

    /**
     * 移除元素
     */
    void remove();

    /**
     * 替換最后返回的元素
     */
    void set(E e);

    /**
     * 插入一個(gè)結(jié)點(diǎn)到最后返回的元素之后
     */
    void add(E e);
}

普通版 ArrayListdie迭代器

調(diào)用方法:list.iterator();

public Iterator<E> iterator() {
        return new Itr();
    }
    private class Itr implements Iterator<E> {
        int cursor;       // 當(dāng)前下標(biāo)
        int lastRet = -1; // 最后一個(gè)元素的索引,沒有返回1
        int expectedModCount = modCount;//創(chuàng)建迭代器時(shí)列表被修改的次數(shù),防止多線程操作。快速失敗
        /**
        * 先檢查一下是否列表已經(jīng)被修改過
        * 做一些簡(jiǎn)單的越界檢查
        * 返回元素,并且記錄下返回元素的下標(biāo)給lastRet,當(dāng)前下標(biāo)+1,
        */
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
        /**
        * 調(diào)用ArrayListdie自身的remove方法移除元素
        * ArrayListdie自身的remove 會(huì)修改modCount的值所以需要更新迭代器的expectedModCount
        * expectedModCount = modCount;
        */
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        //把剩下為next遍歷的所有元素做一個(gè)遍歷消費(fèi)
        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }
        //檢查是否列表已經(jīng)被修改了
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

增強(qiáng)版本 ArrayListdie迭代器

在這里插入圖片描述

實(shí)現(xiàn)了ListIterator接口,ListIterator接口繼承Iterator接口。并且ListItr extends Itr。Itr有的方法其都有。并且增加了

  • hasPrevious 是否有前驅(qū)
  • nextIndex 下一個(gè)索引位置
  • previousIndex 前驅(qū)的索引位置
  • previous 前驅(qū)元素
  • set 替換最后返回的元素
  • add 插入一個(gè)結(jié)點(diǎn)到最后返回的元素之后
private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }
        public boolean hasPrevious() {
            return cursor != 0;
        }
        public int nextIndex() {
            return cursor;
        }
        public int previousIndex() {
            return cursor - 1;
        }
        public E previous() {
            checkForComodification();
            int i = cursor - 1;
            if (i < 0)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i;
            return (E) elementData[lastRet = i];
        }
        //根據(jù)lastRet設(shè)置元素
        public void set(E e) {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                ArrayList.this.set(lastRet, e);
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        public void add(E e) {
            checkForComodification();

            try {
                int i = cursor;
                ArrayList.this.add(i, e);
                cursor = i + 1;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

重點(diǎn)看一下LinkedList的迭代器

調(diào)用方法:list.iterator();

在這里插入圖片描述

重點(diǎn)看下remove方法

private class ListItr implements ListIterator<E> {
        //返回的節(jié)點(diǎn)
        private Node<E> lastReturned;
        //下一個(gè)節(jié)點(diǎn)
        private Node<E> next;
        //下一個(gè)節(jié)點(diǎn)索引
        private int nextIndex;
        //修改次數(shù)
        private int expectedModCount = modCount;

        ListItr(int index) {
            //根據(jù)傳進(jìn)來的數(shù)字設(shè)置next等屬性,默認(rèn)傳0
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }
        //直接調(diào)用節(jié)點(diǎn)的后繼指針
        public E next() {
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();
            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }
        //返回節(jié)點(diǎn)的前驅(qū)
        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();

            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }
        /**
        * 最重要的方法,在LinkedList中按一定規(guī)則移除大量元素時(shí)用這個(gè)方法
        * 為什么會(huì)比list.remove效率高呢;
        */
        public void remove() {
            checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node<E> lastNext = lastReturned.next;
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            expectedModCount++;
        }

        public void set(E e) {
            if (lastReturned == null)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.item = e;
        }

        public void add(E e) {
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }
    }

LinkedList 源碼的remove(int index)的過程是
先逐一移動(dòng)指針,再找到要移除的Node,最后再修改這個(gè)Node前驅(qū)后繼等移除Node。如果有批量元素要按規(guī)則移除的話這么做時(shí)間復(fù)雜度O(n²)。但是使用迭代器是O(n)。

先看看list.remove(idnex)是怎么處理的

LinkedList是雙向鏈表,這里示意圖簡(jiǎn)單畫個(gè)單鏈表
比如要移除鏈表中偶數(shù)元素,先循環(huán)調(diào)用get方法,指針逐漸后移獲得元素,比如獲得index = 1;指針后移兩次才能獲得元素。
當(dāng)發(fā)現(xiàn)元素值為偶數(shù)是。使用idnex移除元素,如list.remove(1);鏈表先Node node(int index)返回該index下的元素,與get方法一樣。然后再做前驅(qū)后繼的修改。所以在remove之前相當(dāng)于做了兩次get請(qǐng)求。導(dǎo)致時(shí)間復(fù)雜度是O(n)。

在這里插入圖片描述

在這里插入圖片描述

繼續(xù)移除下一個(gè)元素需要重新再走一遍鏈表(步驟忽略當(dāng)index大于半數(shù),鏈表倒序查找)

在這里插入圖片描述

以上如果移除偶數(shù)指針做了6次移動(dòng)。

刪除2節(jié)點(diǎn)
get請(qǐng)求移動(dòng)1次,remove(1)移動(dòng)1次。

刪除4節(jié)點(diǎn)
get請(qǐng)求移動(dòng)2次,remove(2)移動(dòng)2次。

迭代器的處理

迭代器的next指針執(zhí)行一次一直向后移動(dòng)的操作。一共只需要移動(dòng)4次。當(dāng)元素越多時(shí)這個(gè)差距會(huì)越明顯。整體上移除批量元素是O(n),而使用list.remove(index)移除批量元素是O(n²)

在這里插入圖片描述

到此這篇關(guān)于java中LinkedList使用迭代器優(yōu)化移除批量元素原理的文章就介紹到這了,更多相關(guān)LinkedList 迭代器批量移除內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 了解Java多線程的可見性與有序性

    了解Java多線程的可見性與有序性

    這篇文章主要介紹了了解Java多線程的可見性與有序性,在Java內(nèi)存模型中,允許編譯器和處理器對(duì)指令進(jìn)行重排序,但是重排序過程不會(huì)影響到單線程程序的執(zhí)行,卻會(huì)影響到多線程并發(fā)執(zhí)行的正確性。,需要的朋友可以參考下
    2019-06-06
  • Java中的String.valueOf()和toString()方法區(qū)別小結(jié)

    Java中的String.valueOf()和toString()方法區(qū)別小結(jié)

    字符串操作是開發(fā)者日常編程任務(wù)中不可或缺的一部分,轉(zhuǎn)換為字符串是一種常見需求,其中最常見的就是String.valueOf()和toString()方法,本文主要介紹了Java中的String.valueOf()和toString()方法區(qū)別小結(jié),感興趣的可以了解一下
    2025-04-04
  • Java Spring集成MapStruct詳情

    Java Spring集成MapStruct詳情

    這篇文章主要介紹了Java Spring集成MapStruct詳情,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-06-06
  • Java中SpringBoot的@Transactional原理

    Java中SpringBoot的@Transactional原理

    這篇文章主要介紹了Java中SpringBoot的@Transactional原理,面向元數(shù)據(jù)遍歷已經(jīng)成為越來越多開發(fā)者的偏好,因此原理從Springboot的EnableTransactionManagement注解說起,需要的朋友可以參考下
    2023-07-07
  • Java SPI的簡(jiǎn)單小實(shí)例

    Java SPI的簡(jiǎn)單小實(shí)例

    這篇文章主要介紹了Java SPI的簡(jiǎn)單小實(shí)例,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • 使用java代碼實(shí)現(xiàn)一個(gè)月內(nèi)不再提醒,通用到期的問題

    使用java代碼實(shí)現(xiàn)一個(gè)月內(nèi)不再提醒,通用到期的問題

    這篇文章主要介紹了使用java代碼實(shí)現(xiàn)一個(gè)月內(nèi)不再提醒,通用到期的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • java轉(zhuǎn)發(fā)和重定向的區(qū)別

    java轉(zhuǎn)發(fā)和重定向的區(qū)別

    這篇文章主要介紹了java轉(zhuǎn)發(fā)和重定向的區(qū)別,需要的朋友可以參考下
    2014-10-10
  • Springboot項(xiàng)目編譯后未能加載靜態(tài)資源文件的問題

    Springboot項(xiàng)目編譯后未能加載靜態(tài)資源文件的問題

    這篇文章主要介紹了Springboot項(xiàng)目編譯后未能加載靜態(tài)資源文件的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • 在SpringBoot中實(shí)現(xiàn)多種方式登錄(通過用戶名、手機(jī)號(hào)、郵箱等)的詳細(xì)指南

    在SpringBoot中實(shí)現(xiàn)多種方式登錄(通過用戶名、手機(jī)號(hào)、郵箱等)的詳細(xì)指南

    今天,我們將跳進(jìn) Spring Boot 的世界,探索如何通過 用戶名、手機(jī)號(hào)、郵箱 等多種方式實(shí)現(xiàn)登錄,而我們要做的就是為他們提供這些選擇,確保他們都能毫無阻礙地進(jìn)入我們的系統(tǒng),感興趣的小伙伴跟著小編一起來看看吧
    2024-11-11
  • Java中的集合ArrayList類常用方法和遍歷

    Java中的集合ArrayList類常用方法和遍歷

    這篇文章主要介紹了Java中的集合ArrayList類常用方法和遍歷,ArrayList 是大小可變的數(shù)組的實(shí)現(xiàn),存儲(chǔ)在內(nèi)的數(shù)據(jù)稱為元素,此類提供一些方法來操作內(nèi)部存儲(chǔ)的元素, ArrayList中可不斷添加元素,其大小也自動(dòng)增長(zhǎng),需要的朋友可以參考下
    2024-01-01

最新評(píng)論

南投市| 洮南市| 贺州市| 巍山| 周至县| 手机| 高要市| 杂多县| 澄迈县| 滦南县| 江津市| 汽车| 响水县| 四川省| 彰武县| 江永县| 河间市| 焉耆| 阆中市| 噶尔县| 永仁县| 澄迈县| 电白县| 利津县| 濮阳县| 瑞安市| 法库县| 仁寿县| 许昌市| 怀安县| 永城市| 高阳县| 丹江口市| 麻栗坡县| 鹤峰县| 宁波市| 克东县| 紫金县| 叶城县| 福州市| 买车|