LinkedList原始碼分析(一)

胖若倆人發表於2018-11-19

LinkedList原始碼分析(一)

這篇文章來自我的部落格

正文之前

之前介紹過了ArrayList的原始碼了,在剛學Java的時候,書籍中就經常拿ArrayListLinkedList來舉例子,學完了ArrayList最常用部分的原始碼後,就打算把LinkedList也學完,原始碼中有兩種操作,一種是列表操作,一種是佇列操作,分兩篇文章來講,今天先講列表操作

今天的內容有這些:

  1. LinkedList 概念介紹
  2. 結點
  3. 類的基本資訊
  4. 構造
  5. 增刪改查

正文

1. 概念介紹

 * Doubly-linked list implementation of the {@code List} and {@code Deque}
 * interfaces.  Implements all optional list operations, and permits all
 * elements (including {@code null}).
 *
 * <p>All of the operations perform as could be expected for a doubly-linked
 * list.  Operations that index into the list will traverse the list from
 * the beginning or the end, whichever is closer to the specified index.
複製程式碼

按照註釋給出的,LinkedList叫做“雙向連結串列”,實現了List(列表)介面和Deque(雙向佇列)介面,支援佇列的操作

對特定的元素的操作,可以從列表的首或者尾開始,哪邊離得近就從哪邊開始

 * <p><strong>Note that this implementation is not synchronized.</strong>
 * If multiple threads access a linked list concurrently, and at least
 * one of the threads modifies the list structurally, it <i>must</i> be
 * synchronized externally.  (A structural modification is any operation
 * that adds or deletes one or more elements; merely setting the value of
 * an element is not a structural modification.)  This is typically
 * accomplished by synchronizing on some object that naturally
 * encapsulates the list.
 *
 * If no such object exists, the list should be "wrapped" using the
 * {@link Collections#synchronizedList Collections.synchronizedList}
 * method.  This is best done at creation time, to prevent accidental
 * unsynchronized access to the list:<pre>
 *   List list = Collections.synchronizedList(new LinkedList(...));</pre>
複製程式碼

ArrayList一樣,這個容器也是非執行緒安全的,如果要在多執行緒環境下使用,也要使用synchronizedList包裝起來

在原始碼中還有一些註釋是關於迭代器的,等到以後的文章中再說明

2. 節點

  1. 節點的表示

需要先統一以下說法,Node叫做節點,Node.item叫做元素

    //當前節點的型別是泛型
    private static class Node<E> {
        E item;
        //前後節點都是Node型別,其中又包括了其當前節點和前後節點
        Node<E> next;
        Node<E> prev;

        Node(Node<E> prev, E element, Node<E> next) {
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }
複製程式碼
  1. 根據索引尋找節點

在查詢的過程要一個一個節點的迭代,所以LinkedList隨機讀取的開銷要比ArrayList

    /**
     * Returns the (non-null) Node at the specified element index.
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);
        //if-else來判斷從頭部還是尾部開始查詢
        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;
        }
    }
複製程式碼

3. 類的基本資訊

先來看看這個類繼承了什麼類,實現了什麼介面

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable{
}
複製程式碼

繼承了AbstractSequentialList(AbstractList的子類),多實現了一個Deque介面,其他的和ArrayList是一樣的

變數:

    //大小
    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;
複製程式碼

4. 構造

  1. 空連結串列
    /**
     * Constructs an empty list.
     */
    public LinkedList() {
    }
複製程式碼
  1. 帶有其他容器元素的連結串列
    public LinkedList(Collection<? extends E> c) {
        //先構造一個空連結串列
        this();
        //新增指定容器的元素的方法,下文講述
        addAll(c);
    }
複製程式碼

5. 增刪改查

因為連結串列是雙向的,所以在增加元素的時候,要設定節點兩邊的指向,接下來說明指向的時候,會說明是向前指向還是向後指向,下文說的刪除指向,就是把指向設為null

主要內容
  • addFirst()
    • linkFirst()
  • addLast()
    • linkLast()
  • add()
    • linkLast()
    • linkBefore()
  • addAll()

從內往外,先將內部方法,再講公用方法:

增加至表頭

LinkedList原始碼分析(一)

    /**
     * Links e as first element.
     */
    //將元素新增至連結串列頭
    private void linkFirst(E e) {
        //先定義一個節點
        final Node<E> f = first;
        //newNode向後指向f
        final Node<E> newNode = new Node<>(null, e, f);
        //新的節點作為第一個節點
        first = newNode;
        //如果f為null,表示連結串列裡只有一個元素,這時候第一個和最後一個都是newNode
        if (f == null)
            last = newNode;
        else
            //f向前指向newNode
            f.prev = newNode;
        //大小加1
        size++;
        modCount++;
    }
複製程式碼
增加至表尾

原理是一樣的,就不畫圖了

    /**
     * Links e as last element.
     */
    //基本套路是一樣的
    void linkLast(E e) {
        final Node<E> l = last;
        //newNode向前指向l
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            //l向後指向newNode
            l.next = newNode;
        size++;
        modCount++;
    }
複製程式碼
增加至指定位置

插入到指定位置,涉及三個元素,兩兩之間有關聯,所有需要有四條指向

LinkedList原始碼分析(一)

    /**
     * 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向前指向newNode
        succ.prev = newNode;
        if (pred == null)
            //如果插入的位置前面沒有節點,則插入的節點作為第一個
            first = newNode;
        else
            //剛才建立的pred節點,向後指向newNode
            pred.next = newNode;
        size++;
        modCount++;
    }
複製程式碼

剛才上面的三個方法都是為下面這些方法服務的:
    //新增至頭部
    public void addFirst(E e) {
        linkFirst(e);
    }
  
  //新增至尾部
  public void addLast(E e) {
        linkLast(e);
    }

    //和上面加至隊尾是等價的,除了有返回值
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    //在指定位置新增節點
    public void add(int index, E element) {
            //檢查元素是否越界
            checkPositionIndex(index);

            /**
             *  private void checkPositionIndex(int index) {
             *      if (!isPositionIndex(index))
             *          throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
             *  }
             */
            //如果索引在最後,直接加至隊尾
            if (index == size)
                linkLast(element);
            else
                //呼叫node()方法尋找節點
                linkBefore(element, node(index));
    }
複製程式碼

還有直接新增另一個容器的元素至連結串列的方法:
  1. 將指定容器的元素新增至指定位置,插入的位置在index元素之前(若index = 1,表示第2個元素,則插入第1個和第2個元素之間)

LinkedList原始碼分析(一)

    public boolean addAll(int index, Collection<? extends E> c) {
        //檢查是否越界
        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;
        }

        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            //如果是第一個節點
            if (pred == null)
                first = newNode;
            else
                //把前一個節點向後指向newNode
                pred.next = newNode;
            //這個在if-else之外,如果沒有這語句,pred節點就固定是那一個節點,所以需要在每一次迴圈內更換節點
            pred = newNode;
        }
        //如果是最後節點
        if (succ == null) {
            last = pred;
        } else {
            //兩個節點之間進行連線
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }
複製程式碼
  1. 將指定容器的元素新增至連結串列尾:
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }
複製程式碼

刪除節點的方式,就是把節點的元素和兩邊的指向設為null,讓GC來收集

主要內容
  • removeFirst()
    • unlinkFirst()
  • removeLast()
    • unlinkLast()
  • remove()
    • unlink()
  • clear()

還是按照相同的順序來:

刪除第一個節點

刪除節點內容,刪除指向

LinkedList原始碼分析(一)

    private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        //把指定節點的內容拿出來,最後返回
        final E element = f.item;
        final Node<E> next = f.next;
        //節點內容設為空
        f.item = null;
        //清空節點的向後指向
        f.next = null; // help GC
        //指定節點的下一個節點作為第一個節點
        first = next;
        //如果沒有下一個節點
        if (next == null)
            last = null;
        else
            //刪除指向
            next.prev = null;
        //改變大小
        size--;
        modCount++;
        return element;
    }
複製程式碼
刪除最後一個節點

步驟是類似的,就畫個圖,程式碼就不解釋了

LinkedList原始碼分析(一)

    /**
     * Unlinks non-null last node l.
     */
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        return element;
    }
複製程式碼
刪除指定節點

LinkedList原始碼分析(一)

    /**
     * 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;
        
        // 如果x是第一個節點,則設定下一個節點為第一節點
        if (prev == null) {
            first = next;
        } else {
            //x的前一個節點直接向後指向後一個節點
            prev.next = next;
            //刪除x的前指向
            x.prev = null;
        }
        
        //如果x是最後一個節點
        if (next == null) {
            //向前指向last節點
            last = prev;
        } else {
            //把後一個節點直接向前指向前一個節點,打個比方,就是1和3節點相連,跳過節點2
            next.prev = prev;
            //刪除指向
            x.next = null;
        }
        //刪除節點內容
        x.item = null;
        //改變大小
        size--;
        modCount++;
        return element;
    }
複製程式碼

這三個刪除的方法寫來是被以下這些方法呼叫的:
    //移除第一個節點
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }
    
    //移除最後節點
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    //刪除特定元素
    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;
    }

    //刪除指定位置元素
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
複製程式碼

清空連結串列

沒有用到上面的方法,直接將所有的設為null

  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
        //不斷迭代,把節點的三個屬性設為null
        for (Node<E> x = first; x != null; ) {
            Node<E> next = x.next;
            x.item = null;
            x.next = null;
            x.prev = null;
            x = next;
        }
        //把首尾設為null,改變大小
        first = last = null;
        size = 0;
        modCount++;
    }
複製程式碼

連結串列中改變節點的方式就一個:set()方法

    public E set(int index, E element) {
        //檢查是否越界
        checkElementIndex(index);
        //根據索引查詢節點
        Node<E> x = node(index);
        //oldVal存放需要改變的內容
        E oldVal = x.item;
        x.item = element;
        //返回改變前的值
        return oldVal;
    }
複製程式碼

  1. 查詢首尾元素:

這個沒什麼好說的,直接上程式碼

    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
複製程式碼
  1. 判斷是否含有某個元素
    public boolean contains(Object o) {
        //indexOf()方法在下面講述
        return indexOf(o) != -1;
    }
複製程式碼
  1. 根據索引查詢
    public E get(int index) {
        checkElementIndex(index);
        //node()方法根據索引來找到節點,在用 .item 來返回節點內容
        return node(index).item;
    }
複製程式碼
  1. 根據元素得出索引

得到特定元素第一次出現的位置:

    public int indexOf(Object o) {
        int index = 0;
        //如果物件為null,則也可以查詢出內容為null的節點的位置
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null)
                    return index;
                index++;
            }
        } else {
            //迭代尋找元素
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item))
                    return index;
                index++;
            }
        }
        return -1;
    }
複製程式碼

得到特定元素最後一次出現的位置,也就是把上面的反過來找:

    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }
複製程式碼

LinkedList基於列表的操作到這裡就介紹完了,下一篇會是基於佇列的操作

相關文章