Java8集合框架——LinkedList源碼分析

java.util.LinkedList

  本文的主要目錄結構:html

 1、LinkedList的特色及與ArrayList的比較

       對比上一篇的ArrayList介紹【傳送門:Java8集合框架——ArrayList源碼分析】,LinkedList因內部實現不一樣,其元素的內部訪問方式也不同。LinkedList的特色大體和ArrayList的比較以下:java

關注的問題點 ArrayList相關結論 LinkedList相關結論

是否容許空的元素node

是否容許重複的元素

元素有序:讀取數據和存放數據的順序一致數組

是否線程安全
隨機訪問的效率 隨機訪問指定索引(數組的索引)的元素快 因須要進行遍歷,隨機訪問指定索引的元素較慢,而利用雙向鏈表的特性,能夠從兩端進行訪問,會使得平均訪問的元素減小一半
順序添加元素的效率

在不涉及擴容時,順序添加元素速度快;安全

當須要擴容時,涉及到元素的複製,相對較慢app

順序添加元素速度快,只是新建一個結點,而後添加結點連接;框架

刪除和插入元素的效率

因涉及到複製和移動後續的元素,相對較慢函數

刪除和插入涉及到遍歷找到相關結點,所以會慢點,可是找到結點後的相關操做會比較快,因不涉及到元素的移動源碼分析

  

2、LinkedList的內部實現

一、內部重要屬性說明

  LinkedList是以雙向鏈表爲基礎實現列表的集合,內部實現結點中,有指向上一個結點 prev 和下一個結點next 的引用,即雙向鏈表,而 E item 即爲實際的存儲元素,實現源碼以下:ui

    private static class Node<E> {
        E item;          // 實際存儲的元素
        Node<E> next;    // 下一個元素的引用
        Node<E> prev;    // 上一個元素的引用

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

   LinkedList內部有幾個重要屬性,好比說保存了元素個數、首結點引用和尾結點引用等,所以要得到LinkedList的首元素和尾元素元素也比較直接。

    // 實際存儲的元素個數
    transient int size = 0;

    /**
     * Pointer to first node.
     * 第一個節點元素的引用
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     */
    transient Node<E> first;

    /**
     * Pointer to last node.
     * 最後一個節點元素的引用
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;

 二、構造函數說明

  一、空構造函數

    /**
     * Constructs an empty list.
     */
    public LinkedList() {
    }

   二、帶參構造函數:經過指定集合構建

    /**
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     * 若是指定集合爲空,會拋出NPE
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

   這個帶參的構造函數其實比較好理解,經過指定集合構建的LinkedList,其實就是建立一個空的 LinkedList,而後把集合裏面的全部元素添加進去。而添加集合元素調用的 addAll(c) ,實際上只是從指定索引處(這裏是從末尾,即 size 處)添加全部的集合元素:addAll(size, c)

    /**
     * Appends all of the elements in the specified collection to the end of
     * this list, in the order that they are returned by the specified
     * collection's iterator.  The behavior of this operation is undefined if
     * the specified collection is modified while the operation is in
     * progress.  (Note that this will occur if the specified collection is
     * this list, and it's nonempty.)
     *
     * 往LinkedList中添加指定集合的全部元素
     *
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(Collection<? extends E> c) {
        // 從索引 size 處添加索引,即從末尾添加節點
        return addAll(size, c);
    }

   再來看看 addAll(size, c) 的具體實現:

    /**
     * Inserts all of the elements in the specified collection into this
     * list, starting at the specified position.  Shifts the element
     * currently at that position (if any) and any subsequent elements to
     * the right (increases their indices).  The new elements will appear
     * in the list in the order that they are returned by the
     * specified collection's iterator.
     *
     * 往LinkedList的指定索引處添加指定集合的全部元素
     *
     * @param index index at which to insert the first element
     *              from the specified collection
     * @param c collection containing elements to be added to this list
     * @return {@code true} if this list changed as a result of the call
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException if the specified collection is null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        // index 的邊界檢查
        checkPositionIndex(index);

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

        Node<E> pred, succ;
        // index == size 表示從鏈表的末尾添加節點元素
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            // 查找指定索引的節點
            // succ 記錄了指定 index 處的索引節點,而 pred 則記錄前一個節點
            // 也便是鏈表斷開處先後的2個節點,中間須要添加指定的集合元素
            succ = node(index);
            pred = succ.prev;
        }

        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            // 構造新節點, 記錄的前節點 pred 恰好是這個要插入到鏈表的新節點的 prev 節點
            Node<E> newNode = new Node<>(pred, e, null);
            // 空鏈表
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        // succ == null 表示是從鏈表尾部添加節點,已經沒有後續節點了
        if (succ == null) {
            last = pred;
        } else {
            // 連接斷開的節點
            pred.next = succ;
            succ.prev = pred;
        }

        // 記錄實際元素個數 size 和已修改次數 modCount
        size += numNew;
        modCount++;
        return true;
    }
    
    // 對下表索引進行邊界檢查
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    /**
     * Tells if the argument is the index of a valid position for an
     * iterator or an add operation.
     * 實際上就是直接與內部屬性 size 的比較, 即必須落在 0 ~ size 之間,由於這是鏈表的實際位置
     */
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }
    /**
     * Returns the (non-null) Node at the specified element index.
     * 查找指定索引的節點
     */
    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;
        }
    }

    下面經過圖示和文字進行具體的說明:  

    List<String> arrayList = new ArrayList<>();
    arrayList.add("01");
    arrayList.add("02");
    arrayList.add("03");
    List<String> linkedList = new LinkedList<>(arrayList);

 

  大體圖示如上。

3、 LinkedList添加元素

一、順序添加元素

       直接上源碼:

    /**
     * Appends the specified element to the end of this list.
     *
     * <p>This method is equivalent to {@link #addLast}.
     *
     * @param e element to be appended to this list
     * @return {@code true} (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        linkLast(e);    // 順序添加新元素,實際上是從鏈表最後添加1個節點
        return true;
    }

    /**
     * Links e as last element.
     */
    void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);    // 新建節點: prev 爲以前的尾節點 last,單連接完成
        last = newNode;    // 新節點即爲尾節點
        if (l == null)
            first = newNode;    // 原來的尾節點爲 null,說明是空鏈表,須要記錄首節點
        else
            l.next = newNode;    // 記錄原尾節點的 next指向,完成雙向連接
        size++;        // 記錄實際元素個數 size 和已修改次數 modCount
        modCount++;
    }

   這段源碼其實挺好理解的,大意就是

  1. 建立引用 l,指向原尾元素 last
  2. 建立新結點 newNode,該節點的 prev 指向保存的原尾節點引用 l,完成鏈表的單向連接
  3. 尾節點引用 last 指向新結點 newNode,做爲新的尾節點
  4. 若原尾節點引用 l 爲空,說明此時剛剛添加第一個元素,以前都沒有元素,是個空鏈表,firstlast 都爲空,則首節點引用 first 指向新建節點 newNode,此時,firstlast都指向同一個節點 newNode;不然,原尾節點的 next 指向 newNode,完成鏈表的雙向連接
  5. 記錄實際元素個數 size 和已修改次數 modCount

二、指定索引插入元素

  1. 判斷是否越界
  2. 若沒有越界,則再判斷是不是尾節點添加,如果,直接順序添加
  3. 若不是,則先找到指定索引的元素結點(參考下一小節),而後執行結點變動操做,和前面的 addAll 中的作法相似,這裏就不細講。
    /**
     * Inserts the specified element at the specified position in this list.
     * Shifts the element currently at that position (if any) and any
     * subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        // index 的邊界檢查
        checkPositionIndex(index);

        // index == size ,則至關於從最後添加元素
        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    /**
     * Inserts element e before non-null Node succ.
     * 在指定節點前添加元素
     */
    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;    // 說明從首節點處插入節點, index = 0
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

 

4、LinkedList查找元素

  根據指定索引查找元素。這裏使用了雙向鏈表的特性,能夠向前或者向後順序查找,即判斷索引落在前半部分(index < (size >> 1)),向後索引,落在後半部分,向前索引,這就能保證最多隻要遍歷一半,提升效率。

    /**
     * Returns the element at the specified position in this list.
     *
     * @param index index of the element to return
     * @return the element at the specified position in this list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        checkElementIndex(index);    // index 的邊界檢查
        return node(index).item;
    }
    /**
     * Returns the (non-null) Node at the specified element index.
     */
    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;
        }
    }

  

5、LinkedList刪除元素

   和ArrayList相似,刪除元素也有2種

  1. 指定索引刪除
  2. 指定元素刪除

  指定元素刪除,是根據元素順序進行判斷直到找到相應的元素的,所以效率不高,從這裏也能夠看到,元素能夠爲null,由於null(使用==)和實際元素(使用equals)的對等判斷是不同的方法;指定索引也是須要先找到索引所對應的元素,而後再刪除元素。

    /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If this list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * {@code i} such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns {@code true} if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     * 移除指定元素
     *
     * @param o element to be removed from this list, if present
     * @return {@code true} if this list contained the specified element
     */
    public boolean remove(Object o) {
        if (o == null) {
            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;
    }
    /**
     * Removes the element at the specified position in this list.  Shifts any
     * subsequent elements to the left (subtracts one from their indices).
     * Returns the element that was removed from the list.
     * 移除指定索引的元素
     *
     * @param index the index of the element to be removed
     * @return the element previously at the specified position
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

    從實現來看,最後刪除元素都是直接調用了unlink(Node n)。

    /**
     * Unlinks non-null node x.
     * 移除一個非空節點
     */
    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;
    }

   這裏大體講一下。說白了,就是結點引用的變動,一個圖就能夠說明,以下。

  1. prev.next = next; 表示上一個元素的 next 指向本結點的 next 實際元素,即跳過本結點連接到下一個結點,如左邊的紅箭頭
  2. next.prev = prev; 表示下一個元素的 prev 指向本結點的 prev 實際元素,即跳過本結點連接到上一個結點,如右邊的紅箭頭。

  這樣便完成了連接的變動。固然這裏還考慮了該元素是不是首元素(首元素 first 下移一格爲 next)、是不是尾元素(尾元素 last 上移一格爲 prev)。以下3種場景(刪除普通節點、刪除首節點或者尾節點、刪除惟一節點)圖示:

 

6、LinkedList修改元素

   能夠到,這裏也是引用了 node(index),要順序找到相應的元素,因此比較慢,可是一旦找到元素,就只會變動相關結點信息,這部分操做仍是比較快的。

 1     /**
 2      * Replaces the element at the specified position in this list with the
 3      * specified element.
 4      *
 5      * @param index index of the element to replace
 6      * @param element element to be stored at the specified position
 7      * @return the element previously at the specified position
 8      * @throws IndexOutOfBoundsException {@inheritDoc}
 9      */
10     public E set(int index, E element) {
11         checkElementIndex(index);
12         Node<E> x = node(index);
13         E oldVal = x.item;
14         x.item = element;
15         return oldVal;
16     }

  做爲 List 的基本功能大體說明如上 。

相關文章
相關標籤/搜索