LinkedList源碼分析

LinkedList 是一個鏈?zhǔn)降臄?shù)據(jù)存儲結(jié)構(gòu), 不是線程安全的 , 不支持隨機(jī)訪問,可序列化胰舆,

實(shí)現(xiàn)的接口

從接口上看骚露,并不支持隨機(jī)訪問的功能,實(shí)際上也沒有插入的功能

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

構(gòu)造函數(shù)

    //鏈?zhǔn)酱鎯Φ暮锰幘驮谟谒嘉粒挥迷跇?gòu)造時荸百,初始化容量,
    public LinkedList() {
    }

    //構(gòu)造時滨攻,初始化數(shù)據(jù)
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

Node

    //節(jié)點(diǎn)結(jié)構(gòu)够话,雙鏈結(jié)構(gòu)
    private static class Node<E> {
        E item;
        Node<E> next; //上一個節(jié)點(diǎn)
        Node<E> prev; //下一個節(jié)點(diǎn)

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }

數(shù)據(jù)鏈的操作

    //這是一個插入元素的操作,相比ArrayList的拷貝操作光绕,性能高很多
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }
    
    //這種查找優(yōu)化方式女嘲,在鏈?zhǔn)酱鎯Y(jié)構(gòu)中很常見,先判斷節(jié)點(diǎn)的大概位置诞帐,再決定遍歷方向
    Node<E> node(int index) {
        // assert isElementIndex(index);

        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }
    
    //釋放節(jié)點(diǎn)
    E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;

        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }

        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;
        return element;
    }

add

    public boolean addAll(int index, Collection<? extends E> c) {
        //檢查下標(biāo)參數(shù)
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);
            pred = succ.prev;
        }

        //重點(diǎn)在這里欣尼,創(chuàng)建鏈結(jié)構(gòu)
        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        
        size += numNew;
        
        //記錄修改次數(shù)
        modCount++;
        return true;
    }

remove

    //這兩種方式,通過下標(biāo)移除元素的方式是性能比較高停蕉。通過元素引用移除愕鼓,是直接暴力的便利搞定的
    public boolean remove(Object o) {
        if (o == null) {
            //這里訪問實(shí)際上,是通過鏈來遍歷的慧起,不支持隨機(jī)訪問
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }
    
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

clear

    public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        //清除操作菇晃,也是遍歷鏈
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        first = last = null;
        size = 0;
        modCount++;
    }

set

    //鏈?zhǔn)浇Y(jié)構(gòu)在替換上性能沒有順序存儲的性能高
    public E set(int index, E element) {
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

insert

    //這是一個插入方法,在性能上會比順序存儲高很多蚓挤,畢竟沒有擴(kuò)容復(fù)制的問題
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

Iterator

    //迭代器的便捷使用的類磺送, 看起來很簡單, 隊(duì)列接口中使用的
    private class DescendingIterator implements Iterator<E> {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

    //迭代器的操作其實(shí)灿意,差不多估灿,通過看構(gòu)造函數(shù),就能大概知道是如何實(shí)現(xiàn)的了
    private class ListItr implements ListIterator<E> {
        //最后一個被遍歷到的節(jié)點(diǎn)元素缤剧,只有先被迭代器訪問到的元素馅袁,才能修改
        private Node<E> lastReturned;
        private Node<E> next;
        private int nextIndex;
        
        //同樣,也是不支持并發(fā)處理數(shù)據(jù)荒辕,這里已經(jīng)做了修改記錄
        private int expectedModCount = modCount;

        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }

        public boolean hasNext() {
            return nextIndex < size;
        }

        public E next() {
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();

            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }

        public boolean hasPrevious() {
            return nextIndex > 0;
        }

        public E previous() {
            checkForComodification();
            if (!hasPrevious())
                throw new NoSuchElementException();

            lastReturned = next = (next == null) ? last : next.prev;
            nextIndex--;
            return lastReturned.item;
        }

        public int nextIndex() {
            return nextIndex;
        }

        public int previousIndex() {
            return nextIndex - 1;
        }

        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++;
        }

        public void forEachRemaining(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            while (modCount == expectedModCount && nextIndex < size) {
                action.accept(next.item);
                lastReturned = next;
                next = next.next;
                nextIndex++;
            }
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市大溜,隨后出現(xiàn)的幾起案子化漆,更是在濱河造成了極大的恐慌,老刑警劉巖钦奋,帶你破解...
    沈念sama閱讀 222,946評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件座云,死亡現(xiàn)場離奇詭異,居然都是意外死亡付材,警方通過查閱死者的電腦和手機(jī)朦拖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,336評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來厌衔,“玉大人璧帝,你說我怎么就攤上這事「皇伲” “怎么了睬隶?”我有些...
    開封第一講書人閱讀 169,716評論 0 364
  • 文/不壞的土叔 我叫張陵,是天一觀的道長页徐。 經(jīng)常有香客問我苏潜,道長,這世上最難降的妖魔是什么变勇? 我笑而不...
    開封第一講書人閱讀 60,222評論 1 300
  • 正文 為了忘掉前任恤左,我火速辦了婚禮,結(jié)果婚禮上搀绣,老公的妹妹穿的比我還像新娘飞袋。我一直安慰自己,他們只是感情好链患,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,223評論 6 398
  • 文/花漫 我一把揭開白布巧鸭。 她就那樣靜靜地躺著,像睡著了一般锣险。 火紅的嫁衣襯著肌膚如雪蹄皱。 梳的紋絲不亂的頭發(fā)上览闰,一...
    開封第一講書人閱讀 52,807評論 1 314
  • 那天芯肤,我揣著相機(jī)與錄音,去河邊找鬼压鉴。 笑死崖咨,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的油吭。 我是一名探鬼主播击蹲,決...
    沈念sama閱讀 41,235評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼署拟,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了歌豺?” 一聲冷哼從身側(cè)響起推穷,我...
    開封第一講書人閱讀 40,189評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎类咧,沒想到半個月后馒铃,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,712評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡痕惋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,775評論 3 343
  • 正文 我和宋清朗相戀三年区宇,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片值戳。...
    茶點(diǎn)故事閱讀 40,926評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡议谷,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出堕虹,到底是詐尸還是另有隱情卧晓,我是刑警寧澤,帶...
    沈念sama閱讀 36,580評論 5 351
  • 正文 年R本政府宣布赴捞,位于F島的核電站禀崖,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏螟炫。R本人自食惡果不足惜波附,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,259評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望昼钻。 院中可真熱鬧掸屡,春花似錦、人聲如沸然评。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,750評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽碗淌。三九已至盏求,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間亿眠,已是汗流浹背碎罚。 一陣腳步聲響...
    開封第一講書人閱讀 33,867評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留纳像,地道東北人荆烈。 一個月前我還...
    沈念sama閱讀 49,368評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親憔购。 傳聞我的和親對象是個殘疾皇子宫峦,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,930評論 2 361

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

  • 移步數(shù)據(jù)結(jié)構(gòu)--容器匯總(java & Android)內(nèi)容: LinkedList 的概述 LinkedList...
    凱玲之戀閱讀 684評論 0 5
  • LinkedList LinkedList是一種可以在任何位置進(jìn)行高效地插入和移除操作的有序序列,它是基于雙向鏈表...
    史路比閱讀 386評論 0 1
  • 前言 上篇文章分析了 ArrayList 的源碼玫鸟,面試過程中經(jīng)常會被面試官來問 LinkedList 和 Arra...
    SmartSean閱讀 272評論 0 0
  • 概要 前面导绷,我們已經(jīng)學(xué)習(xí)了ArrayList,并了解了fail-fast機(jī)制屎飘。這一章我們接著學(xué)習(xí)List的實(shí)現(xiàn)類—...
    程序員歐陽閱讀 230評論 0 2
  • 生活單調(diào)诵次, 學(xué)習(xí),愛與情義 在其中調(diào)劑枚碗。 所以忙碌的時候期待見到你逾一, 休閑的時候感謝有你。 讓單調(diào)與枯燥不在肮雨。
    湛兮閱讀 31評論 0 0