LinkedList 源碼分析

在閱讀LinkedList之前抑钟,建議還是將ArrayList 源碼進行大概了解,其實向外部提供的方法以及設(shè)計思路是差不多的,只是LinkedList數(shù)據(jù)結(jié)構(gòu)不是array了,而是一個鏈表喧半,那我們接下來就一起學(xué)習(xí)下LinkedList的源碼箕速。

首先零截,我們從類圖上來大體了解下 LinkedList 與 ArrayList的關(guān)系:

image.png

可以看出 LinkedList 不只是繼承锭汛、實現(xiàn)了 List 的那套東西荣月,還實現(xiàn)了 Dueue 這個雙向隊列管呵, 什么是雙向隊列呢,就是在隊列兩端都可以“插入”哺窄、“獲取” 數(shù)據(jù)捐下。接下來我們還是以 ArrayList的分析方式去分析LinkedList

基礎(chǔ)成員
    transient int size = 0;

    transient Link<E> voidLink;

    private static final class Link<ET> {
        ET data;

        Link<ET> previous, next;

        Link(ET o, Link<ET> p, Link<ET> n) {
            data = o;
            previous = p;
            next = n;
        }
    }

這是 LinkedList 最基礎(chǔ)的組成部分萌业, Link 這個靜態(tài)內(nèi)部類是LinkedList中每一個單元的類型坷襟,數(shù)據(jù)是datapreviousnext 分別指向鏈表的上游和下游生年;voidLink 可以理解是一個末尾節(jié)點婴程,size是整個list的節(jié)點數(shù)量。從開頭就可以看出抱婉,LinkedList 的數(shù)據(jù)結(jié)構(gòu)是一個雙向鏈表档叔,這樣就避免了ArrayList的自動擴容步驟,雖然在查找的時候占了些劣勢(需要按照鏈表的指向挨個去找蒸绩,不如數(shù)組直接指向角標(biāo)快)衙四。

構(gòu)造方法
   /**
     * Constructs a new empty instance of {@code LinkedList}.
     */
    public LinkedList() {
        voidLink = new Link<E>(null, null, null);
        voidLink.previous = voidLink;
        voidLink.next = voidLink;
    }

    /**
     * Constructs a new instance of {@code LinkedList} that holds all of the
     * elements contained in the specified {@code collection}. The order of the
     * elements in this new {@code LinkedList} will be determined by the
     * iteration order of {@code collection}.
     *
     * @param collection
     *            the collection of elements to add.
     */
    public LinkedList(Collection<? extends E> collection) {
        this();
        addAll(collection);
    }

LinkedList提供了兩個構(gòu)造方法,第一個很簡單患亿,初始化voidLink传蹈,并且將其上下游都指向自己;第二個構(gòu)造方法傳入一個 collection步藕,如果不細究源碼細節(jié)惦界,根據(jù)ArrayList的經(jīng)驗,想必肯定是傳入一個集合漱抓,將集合插入到這個空鏈表中表锻。來舉個例子恕齐,向一個空的 LinkedList 插入 new1 和 new2節(jié)點乞娄,我們用圖示來表達下這個過程:

image.png

上圖標(biāo)注比較明顯,對照代碼不難理解显歧;下邊我們對源碼仪或,從添加、移除士骤、獲取等方面一一進行了解范删,能用圖解盡量少說話:

添加
   /**
     * Adds the specified object at the end of this {@code LinkedList}.
     *
     * @param object
     *            the object to add.
     * @return always true
     */
    @Override
    public boolean add(E object) {
        return addLastImpl(object);
    }

    /**
     * Adds the specified object at the end of this {@code LinkedList}.
     *
     * @param object
     *            the object to add.
     */
    public void addLast(E object) {
        addLastImpl(object);
    }

    private boolean addLastImpl(E object) {
        Link<E> oldLast = voidLink.previous;
        Link<E> newLink = new Link<E>(object, oldLast, voidLink);
        voidLink.previous = newLink;
        oldLast.next = newLink;
        size++;
        modCount++;
        return true;
    }
image.png
   /**
     * Adds the specified object at the beginning of this {@code LinkedList}.
     *
     * @param object
     *            the object to add.
     */
    public void addFirst(E object) {
        addFirstImpl(object);
    }

    private boolean addFirstImpl(E object) {
        Link<E> oldFirst = voidLink.next;
        Link<E> newLink = new Link<E>(object, voidLink, oldFirst);
        voidLink.next = newLink;
        oldFirst.previous = newLink;
        size++;
        modCount++;
        return true;
    }
image.png
   /**
     * Adds the objects in the specified Collection to this {@code LinkedList}.
     *
     * @param collection
     *            the collection of objects.
     * @return {@code true} if this {@code LinkedList} is modified,
     *         {@code false} otherwise.
     */
    @Override
    public boolean addAll(Collection<? extends E> collection) {
        int adding = collection.size();
        if (adding == 0) {
            return false;
        }
        Collection<? extends E> elements = (collection == this) ?
                new ArrayList<E>(collection) : collection;

        Link<E> previous = voidLink.previous;
        for (E e : elements) {
            Link<E> newLink = new Link<E>(e, previous, null);
            previous.next = newLink;
            previous = newLink;
        }
        previous.next = voidLink;
        voidLink.previous = previous;
        size += adding;
        modCount++;
        return true;
    }

這個方法就是構(gòu)造方法里邊調(diào)用的addAll(collection),這里的流程圖在文章開始的時候就已經(jīng)提到了拷肌,若有問題的同學(xué)可以回構(gòu)造方法那里再看看到旦。

    /**
     * Inserts the specified object into this {@code LinkedList} at the
     * specified location. The object is inserted before any previous element at
     * the specified location. If the location is equal to the size of this
     * {@code LinkedList}, the object is added at the end.
     *
     * @param location
     *            the index at which to insert.
     * @param object
     *            the object to add.
     * @throws IndexOutOfBoundsException
     *             if {@code location < 0 || location > size()}
     */
    @Override
    public void add(int location, E object) {
        if (location >= 0 && location <= size) {
            Link<E> link = voidLink;
            if (location < (size / 2)) {
                for (int i = 0; i <= location; i++) {
                    link = link.next;
                }
            } else {
                for (int i = size; i > location; i--) {
                    link = link.previous;
                }
            }
            Link<E> previous = link.previous;
            Link<E> newLink = new Link<E>(object, previous, link);
            previous.next = newLink;
            link.previous = newLink;
            size++;
            modCount++;
        } else {
            throw new IndexOutOfBoundsException();
        }
    }

這個方法的有趣之處是參數(shù)中加了一個location旨巷,最開始查找location位置的link單元時采用了簡單的一種二分查找方式,之后將 含有object 元素的newLink插入到該位置添忘,public boolean addAll(int location, Collection<? extends E> collection)同理采呐,只是批量操作。由于有了 ArrayList 的基礎(chǔ)和上邊的舉例講解搁骑,這里就 不對 “獲取”斧吐、“移除”、“序列化”等做詳細講解了仲器,原理都是一樣的煤率,查找位置使用如上的二分查找,找到了就做一些響應(yīng)的鏈表操作乏冀。

 public boolean offer(E o) {
        return addLastImpl(o);
    }

    public E poll() {
        return size == 0 ? null : removeFirst();
    }

    public E remove() {
        return removeFirstImpl();
    }

    public E peek() {
        return peekFirstImpl();
    }

    private E peekFirstImpl() {
        Link<E> first = voidLink.next;
        return first == voidLink ? null : first.data;
    }

    public E element() {
        return getFirstImpl();
    }

    /**
     * {@inheritDoc}
     *
     * @see java.util.Deque#offerFirst(java.lang.Object)
     * @since 1.6
     */
    public boolean offerFirst(E e) {
        return addFirstImpl(e);
    }

    /**
     * {@inheritDoc}
     *
     * @see java.util.Deque#offerLast(java.lang.Object)
     * @since 1.6
     */
    public boolean offerLast(E e) {
        return addLastImpl(e);
    }

    /**
     * {@inheritDoc}
     *
     * @see java.util.Deque#peekFirst()
     * @since 1.6
     */
    public E peekFirst() {
        return peekFirstImpl();
    }

    /**
     * {@inheritDoc}
     *
     * @see java.util.Deque#peekLast()
     * @since 1.6
     */
    public E peekLast() {
        Link<E> last = voidLink.previous;
        return (last == voidLink) ? null : last.data;
    }

    /**
     * {@inheritDoc}
     *
     * @see java.util.Deque#pollFirst()
     * @since 1.6
     */
    public E pollFirst() {
        return (size == 0) ? null : removeFirstImpl();
    }

    /**
     * {@inheritDoc}
     *
     * @see java.util.Deque#pollLast()
     * @since 1.6
     */
    public E pollLast() {
        return (size == 0) ? null : removeLastImpl();
    }

    /**
     * {@inheritDoc}
     *
     * @see java.util.Deque#pop()
     * @since 1.6
     */
    public E pop() {
        return removeFirstImpl();
    }

    /**
     * {@inheritDoc}
     *
     * @see java.util.Deque#push(java.lang.Object)
     * @since 1.6
     */
    public void push(E e) {
        addFirstImpl(e);
    }

由于LinkedList實現(xiàn)了 Deque 接口 (Deque繼承Queue)蝶糯,上邊這些方法就是具體針對Deque接口的實現(xiàn)方式,反正我是感覺挺亂的辆沦,功能都一樣裳涛,但也要提供好多方法。众辨。端三。。鹃彻。郊闯。。

迭代器

這個我還是很想說的蛛株,LinkedList提供了兩個獲取iterator的方法团赁,分別是

    @Override
    public ListIterator<E> listIterator(int location) {
        return new LinkIterator<E>(this, location);
    }

    public Iterator<E> descendingIterator() {
        return new <E>(this);
    }

從方法名上我們可以看出第一個是正序遍歷,第二個是倒敘遍歷谨履,分別返回了ListIteratorReverseLinkIterator欢摄,這兩個靜態(tài)內(nèi)部類的源碼如下:

private static final class LinkIterator<ET> implements ListIterator<ET> {
        int pos, expectedModCount;

        final LinkedList<ET> list;

        Link<ET> link, lastLink;

        LinkIterator(LinkedList<ET> object, int location) {
            list = object;
            expectedModCount = list.modCount;
            if (location >= 0 && location <= list.size) {
                // pos ends up as -1 if list is empty, it ranges from -1 to
                // list.size - 1
                // if link == voidLink then pos must == -1
                link = list.voidLink;
                if (location < list.size / 2) {
                    for (pos = -1; pos + 1 < location; pos++) {
                        link = link.next;
                    }
                } else {
                    for (pos = list.size; pos >= location; pos--) {
                        link = link.previous;
                    }
                }
            } else {
                throw new IndexOutOfBoundsException();
            }
        }

        public void add(ET object) {
            if (expectedModCount == list.modCount) {
                Link<ET> next = link.next;
                Link<ET> newLink = new Link<ET>(object, link, next);
                link.next = newLink;
                next.previous = newLink;
                link = newLink;
                lastLink = null;
                pos++;
                expectedModCount++;
                list.size++;
                list.modCount++;
            } else {
                throw new ConcurrentModificationException();
            }
        }

        public boolean hasNext() {
            return link.next != list.voidLink;
        }

        public boolean hasPrevious() {
            return link != list.voidLink;
        }

        public ET next() {
            if (expectedModCount == list.modCount) {
                LinkedList.Link<ET> next = link.next;
                if (next != list.voidLink) {
                    lastLink = link = next;
                    pos++;
                    return link.data;
                }
                throw new NoSuchElementException();
            }
            throw new ConcurrentModificationException();
        }

        public int nextIndex() {
            return pos + 1;
        }

        public ET previous() {
            if (expectedModCount == list.modCount) {
                if (link != list.voidLink) {
                    lastLink = link;
                    link = link.previous;
                    pos--;
                    return lastLink.data;
                }
                throw new NoSuchElementException();
            }
            throw new ConcurrentModificationException();
        }

        public int previousIndex() {
            return pos;
        }

        public void remove() {
            if (expectedModCount == list.modCount) {
                if (lastLink != null) {
                    Link<ET> next = lastLink.next;
                    Link<ET> previous = lastLink.previous;
                    next.previous = previous;
                    previous.next = next;
                    if (lastLink == link) {
                        pos--;
                    }
                    link = previous;
                    lastLink = null;
                    expectedModCount++;
                    list.size--;
                    list.modCount++;
                } else {
                    throw new IllegalStateException();
                }
            } else {
                throw new ConcurrentModificationException();
            }
        }

        public void set(ET object) {
            if (expectedModCount == list.modCount) {
                if (lastLink != null) {
                    lastLink.data = object;
                } else {
                    throw new IllegalStateException();
                }
            } else {
                throw new ConcurrentModificationException();
            }
        }
    }

    /*
     * NOTES:descendingIterator is not fail-fast, according to the documentation
     * and test case.
     */
    private class ReverseLinkIterator<ET> implements Iterator<ET> {
        private int expectedModCount;

        private final LinkedList<ET> list;

        private Link<ET> link;

        private boolean canRemove;

        ReverseLinkIterator(LinkedList<ET> linkedList) {
            list = linkedList;
            expectedModCount = list.modCount;
            link = list.voidLink;
            canRemove = false;
        }

        public boolean hasNext() {
            return link.previous != list.voidLink;
        }

        public ET next() {
            if (expectedModCount == list.modCount) {
                if (hasNext()) {
                    link = link.previous;
                    canRemove = true;
                    return link.data;
                }
                throw new NoSuchElementException();
            }
            throw new ConcurrentModificationException();

        }

        public void remove() {
            if (expectedModCount == list.modCount) {
                if (canRemove) {
                    Link<ET> next = link.previous;
                    Link<ET> previous = link.next;
                    next.next = previous;
                    previous.previous = next;
                    link = previous;
                    list.size--;
                    list.modCount++;
                    expectedModCount++;
                    canRemove = false;
                    return;
                }
                throw new IllegalStateException();
            }
            throw new ConcurrentModificationException();
        }
    }

先來看ListIterator這個內(nèi)部類,expectedModCount == list.modCount 判斷和ArrayList一樣笋粟,都是當(dāng)iterator創(chuàng)建好之后怀挠,看LinkedList是否經(jīng)過“添加”、“移除”等操作害捕,expectedModCountiterator初始化時賦值為modCount绿淋,每次對iterator的操作都會判斷二者是否相同,如果直接對LinkedList進行add或者remove操作尝盼,會導(dǎo)致modCount++吞滞,此時如果再對iterator操作時,expectedModCount沒變盾沫,就會拋出ConcurrentModificationException異常裁赠;但ListIteratorArrayList好的地方是不僅提供了remove方法殿漠,還提供了add方法,這樣佩捞,使用iteratorLinkedList操作起碼是單線程安全的凸舵。另外,需要注意的是失尖,ReverseLinkIterator沒有提供add方法啊奄,所以一定注意,使用同一個iterator實例時掀潮,這個過程中不要對LinkedList進行add操作菇夸。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市仪吧,隨后出現(xiàn)的幾起案子庄新,更是在濱河造成了極大的恐慌,老刑警劉巖薯鼠,帶你破解...
    沈念sama閱讀 216,843評論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件择诈,死亡現(xiàn)場離奇詭異,居然都是意外死亡出皇,警方通過查閱死者的電腦和手機羞芍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,538評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來郊艘,“玉大人荷科,你說我怎么就攤上這事∩醋ⅲ” “怎么了畏浆?”我有些...
    開封第一講書人閱讀 163,187評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長狞贱。 經(jīng)常有香客問我刻获,道長,這世上最難降的妖魔是什么瞎嬉? 我笑而不...
    開封第一講書人閱讀 58,264評論 1 292
  • 正文 為了忘掉前任蝎毡,我火速辦了婚禮,結(jié)果婚禮上佑颇,老公的妹妹穿的比我還像新娘顶掉。我一直安慰自己草娜,他們只是感情好挑胸,可當(dāng)我...
    茶點故事閱讀 67,289評論 6 390
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著宰闰,像睡著了一般茬贵。 火紅的嫁衣襯著肌膚如雪簿透。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,231評論 1 299
  • 那天解藻,我揣著相機與錄音老充,去河邊找鬼。 笑死螟左,一個胖子當(dāng)著我的面吹牛啡浊,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播胶背,決...
    沈念sama閱讀 40,116評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼巷嚣,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了钳吟?” 一聲冷哼從身側(cè)響起廷粒,我...
    開封第一講書人閱讀 38,945評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎红且,沒想到半個月后坝茎,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,367評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡暇番,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,581評論 2 333
  • 正文 我和宋清朗相戀三年嗤放,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片壁酬。...
    茶點故事閱讀 39,754評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡斤吐,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出厨喂,到底是詐尸還是另有隱情和措,我是刑警寧澤,帶...
    沈念sama閱讀 35,458評論 5 344
  • 正文 年R本政府宣布蜕煌,位于F島的核電站派阱,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏斜纪。R本人自食惡果不足惜贫母,卻給世界環(huán)境...
    茶點故事閱讀 41,068評論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望盒刚。 院中可真熱鬧腺劣,春花似錦、人聲如沸因块。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,692評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至趾断,卻和暖如春拒名,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背芋酌。 一陣腳步聲響...
    開封第一講書人閱讀 32,842評論 1 269
  • 我被黑心中介騙來泰國打工增显, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人脐帝。 一個月前我還...
    沈念sama閱讀 47,797評論 2 369
  • 正文 我出身青樓同云,卻偏偏與公主長得像堵腹,于是被迫代替她去往敵國和親梢杭。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,654評論 2 354

推薦閱讀更多精彩內(nèi)容