讀Java11 源碼(2)LinkedList

具體的架構圖
在這裏插入圖片描述

1、 LinkedList的屬性

transient int size = 0;
/**
 * 指向頭結點
 */
transient Node<E> first;
/**
 * 指向尾結點
 */
transient Node<E> last;

爲什麼要用transient來修飾?因爲序列化這兩個屬性其實沒有意義的,我們知道,序列化的意義就在於要把數據給保存再來,但是鏈表他是一個節點一個節點的,不是連續存放的,如果你就保存一頭一尾兩個節點就沒有任何意義了,中間的數據要咋辦,你序列化後,那些引用就沒用了,你不能用next來獲取下一個節點了。所以,LinkedList自己寫了writeObject、readObject方法來進行序列化和反序列化,可以看到都用了遍歷來提取、連接數據。

private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    // Write out any hidden serialization magic
    s.defaultWriteObject();

    // Write out size
    s.writeInt(size);

    // Write out all elements in the proper order.
    for (Node<E> x = first; x != null; x = x.next)
        s.writeObject(x.item);
}
private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
    // Read in any hidden serialization magic
    s.defaultReadObject();

    // Read in size
    int size = s.readInt();

    // Read in all elements in the proper order.
    for (int i = 0; i < size; i++)
        linkLast((E)s.readObject());
}

因爲鏈表的構造方法簡單的不行,就不說了。

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

3、增加節點

public void add(int index, E element) {
    checkPositionIndex(index);
    if (index == size)
        linkLast(element);
    else
        linkBefore(element, node(index));
}
private void checkPositionIndex(int index) {
 	if (!isPositionIndex(index))
        throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
void linkBefore(E e, Node<E> succ) {
	// 先找出當前節點的前一個節點
    final Node<E> pred = succ.prev;
    final Node<E> newNode = new Node<>(pred, e, succ);
    succ.prev = newNode;
    if (pred == null)
        first = newNode;
    else
        pred.next = newNode;
    size++;
    modCount++;
}
 /**
  * 根據索引來找節點
  */
Node<E> node(int index) {
    // assert isElementIndex(index);
    if (index < (size >> 1)) {  // 先判斷給的index是否大於二分之一的size
        Node<E> x = first; // 如果小於,從first開始
        for (int i = 0; i < index; i++)
            x = x.next;
        return x;
    } else {
        Node<E> x = last; // 如果大於,就從last開始找
        for (int i = size - 1; i > index; i--)
            x = x.prev;
        return x;
    }
}

以上這段代碼是根據索引找node的代碼,先判斷給的index是否大於二分之一的size,如果小於二分之一的size,從first開始找;如果大於二分之一的size,從last開始找。

4、刪除節點

我們先來看看代碼邏輯

/**
 * 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;1if (prev == null) {
        first = next;2} else {
        prev.next = next;3)
        x.prev = null;  // help GC
    }4if (next == null) {
        last = prev;5} else {
        next.prev = prev;6)
        x.next = null;  // help GC
    }

    x.item = null;
    size--;
    modCount++;
    return element;
}

刪除代碼的邏輯:
(1)先判斷是否爲頭結點,是->(2),否->(3)
(2)first引用直接只想當前節點下一個節點
(3)前一個節點的next引用指向 下一個節點
(4)判斷是否爲最後一個節點;是->(5),否->(6)
(5)最後的last的引用指向前一個節點
(6)下一個節點的pre 指向前一個節點
因爲是雙向鏈表,所以操作更加複雜一點。

5、查詢

public E get(int index) {
	checkElementIndex(index);
	return node(index).item;
}

走的其實就在增加模塊裏就已經講到的node方法。

6、迭代器

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

鏈表這個,依然要注意不用在foreach語法糖裏使用remove這些。要循環刪除,就要用迭代器刪除:

LinkedList<Integer> linkedList = new LinkedList<>();
Iterator<Integer> iterator = linkedList.iterator();
while (iterator.hasNext()) {
    iterator.remove();
}

7、總結

(1)使用LinkedList遍歷的是,如果使用for+index的方式來實現遍歷,那麼效率會很低,建議要使用迭代器的方式。
(2)和ArrayList比起來,插入、刪除頭結點,LinkedList確實快。
(3)因爲需要遍歷,所以在中間位置插入、刪除節點,效率比起ArrayList的慢,其實ArrayList搬運走的是System.arraycopy方法,這個是native修飾的,表示這是個本地方法,這些基本都有用C來實現的方法,直接訪問操作系統底層,效率很高。
(4)尾部插入、刪除,還是ArrayList略快一些。因爲ArrayList純插入數據到數組就行,但 LinkedList 中多了 new 對象以及變換指針指向對象的過程,所以效率要低於 ArrayList。

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