啃碎JDK源碼(六):LinkedList

前言

以前已經寫了幾篇有關Java集合的文章:java

今天咱們來介紹一下另一個容器類:LinkedListnode

正文

LinkedListArrayList同樣是集合List的實現類,雖然較之ArrayList,其使用場景並很少,但一樣有用到的時候,那麼接下來,咱們來認識一下它。segmentfault

public class LinkedList<E> extends AbstractSequentialList<E>
      implements List<E>, Deque<E>, Cloneable, java.io.Serializable{//底層是雙向鏈表
 //元素數量    
 transient int size = 0;
 //第一個結點
 transient Node<E> first;
 //最後一個結點
 transient Node<E> last;
 .....

其實LinkedList底層使用雙向鏈表實現的,能夠看到上面有firstlast兩個Node節點,來看看其內部類Node的定義:數組

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

很簡單,學過鏈表的同窗應該都很清楚。函數

那首先咱們仍是來看看構造函數:性能

public LinkedList() {
}

public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

addAll(Collection<? extends E> c)方法用來添加指定的集合數據到LinkedList中。優化

輔助函數

在去看LinkedListgetadd等方法前,咱們先去看下幾個比較重要的輔助函數:ui

  • 首先是第一個輔助函數linkFirst(E e),該方法用於插入元素到鏈表頭部
/*
 * 插入元素到頭部
 */
private void linkFirst(E e) {
    final Node<E> f = first;
    // 設置newNode的前結點爲null,後結點爲f
    final Node<E> newNode = new Node<>(null, e, f);
    first = newNode;
    if (f == null)
       // 首先連接元素,同時把newNode設爲最後一個結點
        last = newNode;
    else
        f.prev = newNode;
    size++;
    modCount++;
}

回憶一下內部類 Node 的構造函數:Node(Node<E> prev, E element, Node<E> next),三個參數分別前一個結點、元素值以及下一個結點。this

從上面能夠看出在插入元素到鏈表頭部其實建立一個Node結點,讓其 next 指針指向鏈表首結點firstspa

  • 插入元素到鏈表尾部
/*
 * 插入元素到尾部
 */
void linkLast(E e) {
    final Node<E> l = last;
    // 設置newNode的前結點爲l,後結點爲null
    final Node<E> newNode = new Node<>(l, e, null);
    // 新結點變成最後一個結點
    last = newNode;
    // 若l == null說明是首次連接元素,將first也指向新結點
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
    size++;
    // 修改次數+1
    modCount++;
}

插入到尾部和上面插入到頭部的方法也有殊途同歸之妙,這裏就再也不細說。

  • 接着咱們要給定結點前插入元素
/*
 * 在給定結點前插入元素e
 */
void linkBefore(E e, Node<E> succ) {
    final Node<E> pred = succ.prev;
    // 設置newNode的前結點爲pred,後結點爲succ 
    final Node<E> newNode = new Node<>(pred, e, succ);
    succ.prev = newNode;
    if (pred == null)//若是succ是頭結點,將newNode設置爲頭結點
        first = newNode;
    else
        pred.next = newNode;
    size++;
    modCount++;
}

很簡單,就是讓給定結點succprev 指針和前一個結點的 next 指針都指向咱們的新結點就能夠了。

  • 那如何刪除一個結點呢?
/*
 * 刪除鏈表結點
 */
E unlink(Node<E> x) {
    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;//GC回收
    }
    //判斷是不是尾結點
    if (next == null) {
        last = prev;
    } else {
        next.prev = prev;
        x.next = null;//GC回收
    }
    x.item = null;//GC回收
    size--;
    modCount++;
    return element;
}

注意這裏咱們刪除結點 x 後要把x的先後引用包括自身引用都設爲null,這樣JVM垃圾回收纔會幫咱們去回收x,不然會有內存泄漏的隱患。

還有最後一個輔助函數,用來獲取指定位置的結點

/*
 *返回指定位置的結點
 */
Node<E> node(int index) {
    //根據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;
    }
}

這裏有一個值得咱們借鑑的:就是會根據索引的位置來判讀是從頭部仍是尾部遍歷,這也是一個性能的小優化。

image

有了輔助函數後咱們就能夠來看看咱們日常使用的比較多的API了

首先來看看getset方法:

get(int index)方法用來獲取指定位置上的元素

/*
 * 返回指定位置元素
 */
public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}

private void checkElementIndex(int index) {
    if (!isElementIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

private boolean isElementIndex(int index) {
    return index >= 0 && index < size;
}

能夠看到先調用checkElementIndex方法校驗參數,而後調用輔助方法node(int index)獲取元素值。

/*
 * 設置元素
 */
public E set(int index, E element) {
    checkElementIndex(index);
    Node<E> x = node(index);
    E oldVal = x.item;
    x.item = element;
    return oldVal;
}

set(int index, E element)方法用來設置元素,比較簡單再也不細說。

接下來看看另外兩個方法:

peek方法用於返回頭結點,而pool用於刪除頭結點並返回頭結點的值

/*
 * 返回頭結點值,若是鏈表爲空則返回null
 */
public E peek() {
    final Node<E> f = first;
    return (f == null) ? null : f.item;
}

/*
 * 刪除頭結點並返回頭結點值,若是鏈表爲空則返回null
 */
public E poll() {
    final Node<E> f = first;
    return (f == null) ? null : unlinkFirst(f);
}

如今來看看如何刪除一個結點:

/*
 * 默認刪除頭結點
 */
public E remove() {
    return removeFirst();
}
/*
 * 刪除指定位置結點
 */
public E remove(int index) {
    checkElementIndex(index);
    return unlink(node(index));
}
/*
 * 刪除指定結點
 */
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;
}

其實只要搞懂上面幾個輔助函數後,其它的增刪查改就很簡單了。

繼續來看另一個index(Object o)方法,該方法用於返回指定對象在鏈表中的索引

/*
 * 返回指定對象在鏈表中的索引(若是沒有則返回-1)
 * lastIndexOf同理(其實就是從後向前遍歷)
 */
public int indexOf(Object o) {
    int index = 0;
    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;
}

如今咱們如何把LinkedList轉成數組返回呢?來看看toArray方法:

/*
 * 將鏈表包裝成數組返回
 */
public Object[] toArray() {
    Object[] result = new Object[size];
    int i = 0;
    //依次取出結點值放入數組
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;
    return result;
}

還有一個toArray(T[] a)方法,能夠返回指定類型的數組:

/*
 * 將鏈表包裝成指定類型數組返回
 */
public <T> T[] toArray(T[] a) {
    if (a.length < size)//給點的數組長度小於鏈表長度
        //建立一個類型與a同樣,長度爲size的數組
        a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
        
    int i = 0;
    Object[] result = a;//定義result指向給定數組,修改result == 修改a
    //依次把結點值放入result數組
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;

    if (a.length > size)
        a[size] = null;

    return a;
}

迭代器

LinkedListArrayList還有一個比較大的區別是LinkedList除了iterator方法以外還有一個listIterator方法,該迭代器除了向後遍歷數據外,也能夠向前遍歷,正是因爲底層的雙向鏈表結構才能實現。

public ListIterator<E> listIterator(int index) {
    checkPositionIndex(index);//參數校驗
    return new ListItr(index);
}

private class ListItr implements ListIterator<E> {
     private Node<E> lastReturned;//上次越過的結點
     private Node<E> next;//下次越過的結點
    private int nextIndex;//下次越過結點的索引
    private int expectedModCount = modCount;//預期修改次數

    ListItr(int index) {
        next = (index == size) ? null : node(index);//index默認爲0
        nextIndex = index;
    }

     /*判斷是否有下一個元素*/
    public boolean hasNext() {
        return nextIndex < size;
    }
    
     /*向後遍歷,返回越過的元素*/
    public E next() {
        checkForComodification();//fail-fast
        if (!hasNext())
            throw new NoSuchElementException();

        lastReturned = next;
        next = next.next;
        nextIndex++;
        return lastReturned.item;
    }
    
     /*判斷是否有上一個元素*/    
    public boolean hasPrevious() {
        return nextIndex > 0;
    }
    
     /*向前遍歷,返回越過的元素*/
    public E previous() {
        checkForComodification();//fail-fast
        if (!hasPrevious())
            throw new NoSuchElementException();

        lastReturned = next = (next == null) ? last : next.prev;//調用previous後lastReturned = next
        nextIndex--;
        return lastReturned.item;
    }
    
     /*返回下一個越過的元素索引*/
    public int nextIndex() {
        return nextIndex;
    }
    
     /*返回上一個越過的元素索引*/
    public int previousIndex() {
        return nextIndex - 1;
    }
    
     /*刪除元素*/
    public void remove() {
        checkForComodification();//fail-fast
        if (lastReturned == null)
            throw new IllegalStateException();

        Node<E> lastNext = lastReturned.next;
        unlink(lastReturned);//從鏈表中刪除lastReturned,modCount++(該方法會幫你處理結點指針指向)
        if (next == lastReturned)//調用previous後next == lastReturned
            next = lastNext;
        else
            nextIndex--;
            
        lastReturned = null;//GC
        expectedModCount++;
    }
    
     /*設置元素*/
    public void set(E e) {
        if (lastReturned == null)
            throw new IllegalStateException();
        checkForComodification();//fail-fast
        lastReturned.item = e;
    }
    
     /*插入元素*/
    public void add(E e) {
        checkForComodification();//fail-fast
        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();
    }
    
     /*fail-fast*/
    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

總結

今天有關LinkedList的源碼分就暫時先到這裏,其實若是理解了鏈表結構那麼上面源碼應該不是很難,若是有什麼不對的地方請多多指教。

image

相關文章
相關標籤/搜索