Java容器——LinkedList(Java9 )原始碼解析
LinkedList繼承自List,是一種常用的容器。雖然同為ArrayList和LinkedList同為List,但二者的實現方式完全不同,導致二者的效能和使用場景都有較大的不同,本文將從原始碼角度解析LinkedList。
LinkedList的類圖關係如上圖所示。簡而言之,LinkedList是實現了可複製,可序列化的一種雙向連結串列。雖然它同時實現了List和Deque介面,從內在基因上個人更傾向於將其歸於雙向佇列。下面就從原始碼的角度看一看LinkedList的實現。
一 成員變數
/** * * LinkedList的結點 */ 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; } } // size of list transient int size = 0; /** * Pointer to first node */ transient Node<T> first; /** * Pointer to lastnode */ transient Node<T> last;
這裡列出了幾個關鍵的變數。首先重中之重是Node,即LinkedList的結點。每一個LinkedList由一個一個的Node連線起來。Node由三部分組成,前驅指標指向前一個Node,後繼指標指向後面的Node,結點元素儲存值。其他幾個變數從字面上也都很容易理解。
二 關鍵函式
1 建構函式
/** * 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的建構函式有兩個,一個是從集合從生成List,一個是空的建構函式。對於空的建構函式,size初始化為0,首節點和尾結點都為空指標。
2 增刪元素
LinkedList同時實現了List和Deque介面,這兩種介面對資料的操作有不同的介面函式和表現形式,不過從本質上說,都是針對Node的操作,這裡我們著重關注增加和刪除結點,其他的介面都可以由此衍變而來。
/**
* 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) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/**
* 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.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
/**
* 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;
}
}
增加元素看add這個函式就夠了。首先判斷增加元素的下標是否合法,增加位置等於List長度則在尾結點後新增Node。更為一般的,則是在任意位置新增元素。新增時首先要找到這個結點要放置的位置,找位置的方式是先將List長度二分,然後根據index和二分位置的比較來決定是在前半部分還是後半部分遍歷尋找。由於LinkedList遍歷需要從每一個結點找到指向下一個結點的指標,再如此迴圈,所以這種遍歷比較耗時,時間複雜度為O(n)(n為List長度)。而在LinkedList的開頭和結尾處新增元素則很快,只需要O(1)常數時間。
/**
* 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) {
checkElementIndex(index);
return unlink(node(index));
}
/**
* 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;
}
刪除結點同樣也需要找到它的位置。如果前驅結點為空,說明是List首部,則後面的結點作為首結點。如果後續結點為空,則前驅結點作為List尾。如果在佇列中間,則將前後兩個結點連線起來,並將自身清空,縮短佇列長度。可以看到,刪除的操作並不複雜,主要時間在查詢結點位置上,同樣也是O(n)的複雜度。
3 方法示例
/**
* 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;
}
/**
* 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<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
/**
* 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);
}
/**
* 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();
}
可以看到,常用的get,set方法,主要是在找元素的位置。其他如常見的佇列方法,都是在add,remove的基礎上做了封裝。
三 小結
LinkedList是一個List,也是一個Deque,有較為豐富的介面。不同於ArrayList可以用下標找到地址,LinkedList的增刪改查都需要遍歷List,處理起來比較耗時,因此適用於經常對首尾元素操作且效能要求不高的場景。此外,由於LinkedList是動態申請每一塊記憶體,對記憶體的連續性要求不高,在虛擬機器堆記憶體較少的情況下可以考慮使用。