LinkedList源碼解析

LinkedList<T>類介紹

上一篇文章咱們介紹了JDK中ArrayList的實現,ArrayList底層結構是一個Object[]數組,經過拷貝,複製等一系列封裝的操做,將數組封裝爲一個幾乎是無限的容器。今天咱們來介紹JDK中List接口的另一種實現,基於鏈表結構的LinkedList。ArrayList因爲基於數組,因此在隨機訪問方面優點比較明顯,在刪除、插入方面性能會相對偏弱些(固然與刪除、插入的位置有很大關係)。那麼LinkedList有哪些優點呢?它在刪除、插入方面的操做很簡單(只是調整相關指針而已)。可是隨機訪問方面要遜色寫。下面咱們仍是從源碼上來看下這種鏈表結構的List。node

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;
複製代碼

咱們看到字段很是少,size表示當前節點數量,first指向鏈表的起始元素、last指向鏈表的最後一個元素。數組

Node結構

從上面主要字段看出,LinkedList鏈表的Item就是一個Node結構,那麼Node結構是怎樣的呢?源碼以下:bash

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;
    }
}
複製代碼

咱們看到Node結構包含一個前驅prev指針,item(value)、後繼next指針三個部分。結合上面的描述,咱們知道了LinkedList的主要結構。如圖:數據結構

第一個節點的prev指向NULL,最後一個節點的next指向NULL。其他節點經過prev與next串聯起來,LinkedList提供了從任意節點都能進行向前或前後遍歷的能力。

LinkedList相關方法解析

構造函數

/**
 * 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
 */
public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}
複製代碼

因爲LinkedList是經過prev與next指針連接起來的,有元素添加時只須要一個個設置指針將其連接起來便可,因此構造函數相對較簡潔。咱們重點來看下第二個構造函數中的addAll方法。app

addAll方法

/**
 * 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.)
 *
 * @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) {
    return 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.'
 *
 * @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) {
    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
            pred.next = newNode;
        pred = newNode;
    }

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

    size += numNew;
    modCount++;
    return true;
}

/**
 * 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;
    }
}
複製代碼

addAll方法是將Collection集合插入鏈表。下面咱們來仔細分析整個過程(涉及比較多的指針操做)。函數

  • 首先代碼檢查index的值的正確性,若是index位置不合理會直接拋出異常。
  • 而後將待插入集合轉化成數組,判斷集合長度。
  • 根據index值,分別設置pred和succ指針。若是插入的位置是當前鏈表尾部,那麼pred指向最後一個元素,succ暫時設置爲NULL便可。若是插入位置在鏈表中間,那麼先經過node方法找到當前鏈表的index位置的元素,succ指向它。pred指向待插入位置的前一個節點,succ指向當前index位置的節點,新插入的節點就是在pred和succ節點之間。
  • for循環建立Node節點,先將pred.next指向新建立的節點,而後pred指向後移,指向新建立的Node節點,重複上述過程,這樣一個個節點就被建立,連接起來了。
  • 最後根據狀況不一樣,將succ指向的那個節點做爲最後的節點,固然若是succ爲NULL的話,last指針指向pred。

removeFirst()方法和removeLast()方法

removeFirst方法會返回當前鏈表的頭部節點值,而後將頭結點指向下一個節點,咱們經過源碼來分析:性能

/**
 * Removes and returns the first element from this list.
 *
 * @return the first element from this list
 * @throws NoSuchElementException if this list is empty
 */
public E removeFirst() {
    final Node<E> f = first;
    if (f == null)
        throw new NoSuchElementException();
    return unlinkFirst(f);
}

/**
 * Unlinks non-null first node f.
 */
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;
}
複製代碼

咱們看到主要邏輯在unlinkFirst方法中,邏輯仍是比較清晰的,first指針指向next節點,該節點做爲新的鏈表頭部,只是最後須要處理下邊界值(next==null)的狀況。removeLast方法相似,你們能夠去分析源碼。ui

addFirst方法和addLast()方法

addFirst方法是將新節點插入鏈表,而且將新節點做爲鏈表頭部,下面咱們來看源碼:this

/**
 * Inserts the specified element at the beginning of this list.
 *
 * @param e the element to add
 */
public void addFirst(E e) {
    linkFirst(e);
}

/**
 * Links e as first element.
 */
private void linkFirst(E e) {
    final Node<E> f = first;
    final Node<E> newNode = new Node<>(null, e, f);
    first = newNode;
    if (f == null)
        last = newNode;
    else
        f.prev = newNode;
    size++;
    modCount++;
}
複製代碼

代碼邏輯比較清晰,newNode節點在建立時,因爲是做爲新的頭結點的,因此prev必須是NULL的,next是指向當前頭結點f。接下來就是設置first,處理邊界值了。
下面咱們來看下addLast方法,源碼以下:spa

/**
 * Appends the specified element to the end of this list.
 *
 * <p>This method is equivalent to {@link #add}.
 *
 * @param e the element to add
 */
public void addLast(E e) {
    linkLast(e);
}

/**
 * Links e as last element.
 */
void linkLast(E e) {
    final Node<E> l = last;
    final Node<E> newNode = new Node<>(l, e, null);
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    modCount++;
}
複製代碼

add方法和remove方法

這兩個方法是咱們使用頻率很高的方法,咱們來看下其內部實現:

/**
 * 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);
    return true;
}

/**
 * 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;
}

/**
 * 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;
}
複製代碼

咱們看到add方法其實就是對linkLast方法的封裝(固然,這是末尾添加)。remove方法邏輯會複雜些,須要先找到指定節點,而後調用unlink方法。
unlink方法解析
咱們看到unlink方法首先將須要刪除的節點的prev和next保存起來,由於後面須要將二者鏈接起來。而後將prev和next分別判斷設置(包括邊界值的考慮),最後將x節點的數據設置爲NULL。

clear方法

LinkedList鏈表結構的,它的clear方法是如何實現的呢?咱們來看下:

/**
 * Removes all of the elements from this list.
 * The list will be empty after this call returns.
 */
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++;
}
複製代碼

代碼仍是比較清晰的,就是從頭結點開始,將Node節點一個個的設置爲NULL,方便GC回收。

LinkedList與隊列操做

有數據結構基礎的同窗應該都知道隊列的結構,這是一種先進先出的結構。從JDK1.5開始,LinkedList內部集成了隊列的操做,LinkedList能夠當作一個基本的隊列進行使用。下面咱們從隊列的角度來看下LinkedList提供的相關方法。

peek、poll、element、remove方法

/**
 * Retrieves, but does not remove, the head (first element) of this list.
 *
 * @return the head of this list, or {@code null} if this list is empty
 * @since 1.5
 */
public E peek() {
    final Node<E> f = first;
    return (f == null) ? null : f.item;
}

/**
 * Retrieves, but does not remove, the head (first element) of this list.
 *
 * @return the head of this list
 * @throws NoSuchElementException if this list is empty
 * @since 1.5
 */
public E element() {
    return getFirst();
}

/**
 * Retrieves and removes the head (first element) of this list.
 *
 * @return the head of this list, or {@code null} if this list is empty
 * @since 1.5
 */
public E poll() {
    final Node<E> f = first;
    return (f == null) ? null : unlinkFirst(f);
}

/**
 * Retrieves and removes the head (first element) of this list.
 *
 * @return the head of this list
 * @throws NoSuchElementException if this list is empty
 * @since 1.5
 */
public E remove() {
    return removeFirst();
}
複製代碼

從上面的方法,咱們知道peek、element方法只返回隊列頭部數據,不移除頭部。而poll、remove方法返回隊列頭部數據的同是,還會移除頭部。

offer方法

/**
 * Adds the specified element as the tail (last element) of this list.
 *
 * @param e the element to add
 * @return {@code true} (as specified by {@link Queue#offer})
 * @since 1.5
 */
public boolean offer(E e) {
    return add(e);
}
複製代碼

從上面的代碼中咱們看到,offer方法其實就是入隊操做。

LinkedList與雙端隊列

上面咱們介紹了使用LinkedList來做爲隊列的相關方法,在JDK6中添加相關方法讓LinkedList支持雙端隊列。源代碼以下:

// Deque operations
/**
 * Inserts the specified element at the front of this list.
 *
 * @param e the element to insert
 * @return {@code true} (as specified by {@link Deque#offerFirst})
 * @since 1.6
 */
public boolean offerFirst(E e) {
    addFirst(e);
    return true;
}

/**
 * Inserts the specified element at the end of this list.
 *
 * @param e the element to insert
 * @return {@code true} (as specified by {@link Deque#offerLast})
 * @since 1.6
 */
public boolean offerLast(E e) {
    addLast(e);
    return true;
}

/**
 * Retrieves, but does not remove, the first element of this list,
 * or returns {@code null} if this list is empty.
 *
 * @return the first element of this list, or {@code null}
 *         if this list is empty
 * @since 1.6
 */
public E peekFirst() {
    final Node<E> f = first;
    return (f == null) ? null : f.item;
 }

/**
 * Retrieves, but does not remove, the last element of this list,
 * or returns {@code null} if this list is empty.
 *
 * @return the last element of this list, or {@code null}
 *         if this list is empty
 * @since 1.6
 */
public E peekLast() {
    final Node<E> l = last;
    return (l == null) ? null : l.item;
}

/**
 * Retrieves and removes the first element of this list,
 * or returns {@code null} if this list is empty.
 *
 * @return the first element of this list, or {@code null} if
 *     this list is empty
 * @since 1.6
 */
public E pollFirst() {
    final Node<E> f = first;
    return (f == null) ? null : unlinkFirst(f);
}

/**
 * Retrieves and removes the last element of this list,
 * or returns {@code null} if this list is empty.
 *
 * @return the last element of this list, or {@code null} if
 *     this list is empty
 * @since 1.6
 */
public E pollLast() {
    final Node<E> l = last;
    return (l == null) ? null : unlinkLast(l);
}
複製代碼

上面的代碼邏輯比較清楚,就不詳細介紹了。

LinkedList與棧(Stack)

堆棧大夥確定很熟悉,是一種先進後出的結構。相似於疊盤子,通常咱們使用的時候確定從最上面拿取。棧也是這樣,最後進入的,最早出去。LinkedList在JDK6的時候也添加了對棧的支持。咱們來看相關源碼:

/**
 * Pushes an element onto the stack represented by this list.  In other
 * words, inserts the element at the front of this list.
 *
 * <p>This method is equivalent to {@link #addFirst}.
 *
 * @param e the element to push
 * @since 1.6
 */
public void push(E e) {
    addFirst(e);
}

/**
 * Pops an element from the stack represented by this list.  In other
 * words, removes and returns the first element of this list.
 *
 * <p>This method is equivalent to {@link #removeFirst()}.
 *
 * @return the element at the front of this list (which is the top
 *         of the stack represented by this list)
 * @throws NoSuchElementException if this list is empty
 * @since 1.6
 */
public E pop() {
    return removeFirst();
}
複製代碼

咱們看到LinkedList封裝的push和pop操做其實就是對first頭結點的操做。經過對頭結點不短了的push、pop來模擬堆棧先進後出的結構。

LinkedList與迭代器

private class ListItr implements ListIterator<E> {
    private Node<E> lastReturned;
    private Node<E> next;
    private int nextIndex;
    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();
    }
}
複製代碼

從上面的迭代器的源碼咱們能夠知道如下幾點:

  • 一、LinkedList經過自定義迭代器實現了往前日後兩個方向的遍歷。
  • 二、remove方法中next == lastReturned條件的判斷是針對上一次對鏈表進行了previous操做後進行的判斷。由於上一次previous操做後next指針會「懸空」。須要將其設置爲next節點。

LinkedList遍歷相關問題

對於集合來講,遍歷是很是常規的操做。可是對於LinkedList來講,遍歷的時候須要選擇合適的方法,由於不合理的方法對於性能有很是大的差異。咱們經過例子來看:

List<String> list=new LinkedList<>();
for(int i=0;i<10000;i++) {
	list.add(String.valueOf(i));
}

//遍歷方法一
long time=System.currentTimeMillis();
for(int i=0;i<list.size();i++) {
	list.get(i);
}
System.out.println(System.currentTimeMillis()-time);


time=System.currentTimeMillis();
Iterator<String> iterator=list.iterator();
while (iterator.hasNext()) {
	iterator.next();
}
iterator.remove();
System.out.println(System.currentTimeMillis()-time);
複製代碼

輸出以下:

size:10000的狀況
120
2
size:100000的狀況
28949
2
複製代碼

一樣是遍歷方法,爲何性能差異幾十倍,設置上萬倍呢?研究過源碼的同窗應該能發現其中的奧祕。咱們來看get方法的邏輯:

/**
 * 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);
    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;
    }
}
複製代碼

咱們看到,咱們get(index)的時候,都須要從頭,或者從尾部慢慢循環過來。get(4000)的時候須要從0-4000進行遍歷。get(4001)的時候仍是須要從0-4001進行遍歷。作了無數的無用功。可是迭代器就不同了。迭代器經過next指針,能指向下一個節點,無需作額外的遍歷,速度很是快。

總結

  • 一、LinkedList在添加及修改時候效率較高,只須要設置先後節點便可(ArrayList還須要拷貝先後數據)。
  • 二、LinkedList不一樣的遍歷性能差距極大,推薦使用迭代器進行遍歷。LinkedList在隨機訪問方面性能通常(ArrayList隨機方法可使用基地址+偏移量的方式訪問)
  • LinkedList提供做爲隊列、堆棧的相關方法。
相關文章
相關標籤/搜索