深入剖析LinkedList的底層源碼,再也不怕面試官問了!

寫在前面: 我是「揚帆向海」,這個暱稱來源於我的名字以及女朋友的名字。我熱愛技術、熱愛開源、熱愛編程。技術是開源的、知識是共享的

這博客是對自己學習的一點點總結及記錄,如果您對 Java算法 感興趣,可以關注我的動態,我們一起學習。

用知識改變命運,讓我們的家人過上更好的生活

相關文章:

深入剖析ArrayList的底層源碼


一、LinkedList介紹及其源碼剖析

繼承結構
在這裏插入圖片描述

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
  • LinkedList 繼承了AbstractSequentialList類,實現了List接口、Deque 接口、Cloneable接口、java.io.Serializable接口。
  • LinkedList 實現了 List 接口,即能對它進行隊列操作,提供了相關的添加、刪除、修改、遍歷等功能。
  • LinkedList 實現了 Deque 接口,即能將LinkedList當作雙端隊列使用。
  • LinkedList 實現了Cloneable接口,即覆蓋了函數clone(),所以它能被克隆。
  • LinkedList 實現java.io.Serializable接口,這意味着LinkedList支持序列化,能通過序列化進行傳輸。

LinkedList屬性源碼剖析

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
	// 雙向鏈表的節點個數
    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;

}

從以上源碼可以看出,LinkedList 的屬性比較少。分別是:

  • size : 雙向鏈表的節點個數
  • first: 雙向鏈表指向頭節點的指針
  • last: 雙向鏈表指向尾節點的指針

注意:first 和 last 是由引用類型Node連接的,這是它的一個內部類。

Node源碼剖析

private static class Node<E> {
	// item表示當前存儲元素
    E item;
    // next表示當前節點的後置節點
    Node<E> next;
    // prev表示當前節點的前置節點
    Node<E> prev;

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

LinkedList 是通過雙向鏈表實現的,而雙向鏈表就是通過Node類來實現的,Node類中通過item變量存儲當前元素,通過next變量指向當前節點的下一個節點,通過prev變量指向當前節點的上一個節點。

二、構造方法及其源碼剖析

1. 無參構造方法

源碼剖析

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

LinkedList 的無參構造就是構造一個空的list集合

2. Collection<? extends E>型構造方法

源碼剖析

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

從源碼中分析可得:

構造一個包含指定集合的元素的列表,按照它們由集合的迭代器返回的順序。

三、常用方法及其源碼剖析

1. add() 方法

add(E e) 方法,將指定的元素追加到此列表的末尾

源碼剖析

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

其中,調用了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;
    // 如果最後一個節點爲null,則表示鏈表爲空,則將newNode賦值給first節點
    if (l == null)
        first = newNode;
    else
    	// 否則尾節點的last指向 newNode
        l.next = newNode;
    // 元素的個數加1
    size++;
    // 修改次數自增
    modCount++;
}

總結

  • 第一步,獲取鏈表的最後一個節點
  • 第二步,創建一個新節點
  • 第三步,使新的一個節點爲最後一個節點
  • 第四步,如果最後一個節點爲null,則表示鏈表爲空,則將newNode賦值給first節點;否則尾節點的last指向 newNode

add(int index, E element) 方法,在指定位置插入元素

源碼剖析

/**
 * 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,直接在鏈表的最後插入元素,相當於add(E e)方法
    if (index == size)
        linkLast(element);
    else
    	// 否則調用node方法將index位置的節點找出,接着調用linkBefore 方法
        linkBefore(element, node(index));
}

總結:

  • 首先檢查索引index的位置,看下標是否越界
  • 如果index==size,直接在鏈表的最後插入元素,相當於add(E e)方法
  • 否則調用node方法將index位置的節點找出,接着調用linkBefore 方法

其中,調用checkPositionIndex()方法,檢查索引index的位置

源碼剖析

private void checkPositionIndex(int index) {
    if (!isPositionIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}

在增加元素的時候,調用了linkBefore()方法,在非null節點succ之前插入元素e

源碼剖析

/**
 * Inserts element e before non-null Node succ.
 */
void linkBefore(E e, Node<E> succ) {
    // assert succ != null;
    // 指定節點的前驅
    final Node<E> pred = succ.prev;
    // 創建新的節點,前驅節點爲succ的前驅節點,後續節點爲succ,則e元素就是插入在succ之前的
    final Node<E> newNode = new Node<>(pred, e, succ);
    // 構建雙向鏈表,succ的前驅節點爲新的節點
    succ.prev = newNode;
    // 如果前驅節點爲null,則把newNode賦值給first
    if (pred == null)
        first = newNode;
    else
    	// 構建雙向列表
        pred.next = newNode;
    // 元素的個數加    
    size++;
    // 修改次數自增
    modCount++;
}

總結

  • 指定節點的前驅
  • 創建新的節點,前驅節點爲succ的前驅節點,後續節點爲succ,則e元素就是插入在succ之前的
  • 構建雙向鏈表,succ的前驅節點爲新的節點
  • 如果前驅節點爲null,則把newNode賦值給first;否則構建雙向列表

2. remove() 方法

remove() 方法 刪除這個列表的頭(第一個元素)

源碼剖析

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

其中,調用了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);
}

remove(int index) 方法,刪除指定位置的元素

源碼剖析

/**
 * 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) {
	// 檢查索引index的位置
    checkElementIndex(index);
    // 調用node方法獲取節點,接着調用unlink(E e)方法	
    return unlink(node(index));
}

總結

  • 檢查索引index的位置
  • 調用node方法獲取節點,接着調用unlink(E e)方法

其中,調用了unlink()方法

源碼剖析

/**
 * 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;
    }
	
	// 把item置爲null,讓垃圾回收器回收
    x.item = null;
     // 移除一個節點,size自減
    size--;
    modCount++;
    return element;
}

3. set() 方法

set(int index, E element)方法,將指定下標處的元素修改成指定值

源碼剖析

/**
 * Replaces the element at the specified position in this list with the
 * specified element.
 *
 * @param index index of the element to replace
 * @param element element to be stored at the specified position
 * @return the element previously at the specified position
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E set(int index, E element) {
    checkElementIndex(index);
    // 通過node(int index)找到對應下標的元素
    Node<E> x = node(index);
     // 取出該節點的元素,供返回使用
    E oldVal = x.item;
     // 用新元素替換舊元素
    x.item = element;
    // 返回舊元素
    return oldVal;
}

總結:

先通過node(int index)找到對應下標的元素,然後修改Node中item的值。

4. get() 方法

get(int index) 返回此列表中指定位置的元素

源碼剖析

public E get(int index) {
	// 檢查索引index的位置
    checkElementIndex(index);
    // 調用node()方法
    return node(index).item;
}

在此調用了node()方法

源碼剖析

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

總結

這裏查詢使用的是先從中間分一半查找,根據下標是否超過鏈表長度的一半,來選擇從前半部分開始遍歷查找,還是從後半部分開始遍歷查找。

  • 如果index小於size的一半,就從首節點開始遍歷,一直獲取x的下一個節點
  • 如果index大於或等於size的一半,就從尾節點開始遍歷,一直獲取x的上一個節點

四、雙端隊列操作方法的源碼剖析

offerFirst(E e) 方法,將指定的元素插入到此集合列表的前面,也就是將將元素添加到首部

源碼剖析

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

offerLast(E e)方法,將指定的元素插入到此集合列表的末尾,也就是將元素添加到尾部

源碼剖析

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

peekFirst()方法,獲取此集合列表的第一個元素值

源碼剖析

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

peekLast()方法,獲取此集合列表的最後一個元素值

源碼剖析

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

pollFirst()方法,刪除此集合列表的第一個元素,如果爲null,則會返回null

源碼剖析

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

pollLast()方法,刪除此集合列表的最後一個元素,如果爲null會返回null

源碼剖析

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

push(E e)方法,將元素添加到此集合列表的首部

源碼剖析

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

pop()方法,刪除並返回此集合列表的第一個元素,如果爲null會拋出異常

源碼剖析

/**
 * 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
 */
 //刪除首部,如果爲null會拋出異常
public E pop() {
    return removeFirst();
}

removeFirstOccurrence(Object o)方法,刪除集合中元素值等於o的第一個元素值

源碼剖析

/**
 * Removes the first occurrence of the specified element in this
 * list (when traversing the list from head to tail).  If the list
 * does not contain the element, it is unchanged.
 *
 * @param o element to be removed from this list, if present
 * @return {@code true} if the list contained the specified element
 * @since 1.6
 */
public boolean removeFirstOccurrence(Object o) {
    return remove(o);
}

注意

removeFirstOccurrence()和remove方法是一樣的,因爲它的內部調用了remove方法

removeLastOccurrence(Object o)方法,刪除集合中元素值等於o的最後一個元素值

源碼剖析

/**
 * Removes the last occurrence of the specified element in this
 * list (when traversing the list from head to tail).  If the list
 * does not contain the element, it is unchanged.
 *
 * @param o element to be removed from this list, if present
 * @return {@code true} if the list contained the specified element
 * @since 1.6
 */
public boolean removeLastOccurrence(Object o) {
	//因爲LinkedList中的元素允許存在null值,所以需要進行null判斷
    if (o == null) {
    	// 從最後一個節點往前開始遍歷
        for (Node<E> x = last; x != null; x = x.prev) {
            if (x.item == null) {
            	 // 調用unlink方法刪除指定節點
                unlink(x);
                return true;
            }
        }
    } else {
    	// 否則元素不爲空,進行遍歷
        for (Node<E> x = last; x != null; x = x.prev) {
            if (o.equals(x.item)) {
                unlink(x);
                return true;
            }
        }
    }
    return false;
}

五、ArrayList 和 LinkedList 的區別

二者都 線程不安全,但是效率比 Vector 的高

  • ArrayList 底層是以 數組 的形式保存數據,隨機訪問集合中的元素比LinkedList 快(原因是 LinkedList 要移動指針);
  • LinkedList 內部以 鏈表 的形式保存集合裏面數據,它隨機訪問集合中的元素性能比較慢,但是新增和刪除時速度比 ArrayList 快(原因是 ArrayList 要移動數據)。

由於水平有限,本博客難免有不足,懇請各位大佬不吝賜教!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章