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是動態申請每一塊內存,對內存的連續性要求不高,在虛擬機堆內存較少的情況下可以考慮使用。