在List
中,LinkedList
也是一個非常常見的實現,LinkedList
內部是一個雙向鏈表。所有的元素都會以節點的形式保存在內存中,然后通過對鏈表的操作,來變動這個數據結構。
節點對象
上面提到所有的元素都會以節點的形式保存在內存中, 那么來觀察這個內部的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;
}
}
由上述代碼可以看出,這個節點擁有這樣幾個重要信息:
- item:當前元素值
- next:下一個節點
- prev:前一個節點
另外在這個類中,最重要的兩個參數頭節點和尾節點:
transient Node<E> first;
transient Node<E> last;
初始化
相比ArrayList
,LinkedList
只有兩個構造方法:
public LinkedList() {
}
public LinkedList(Collection<? extends E> c) {
this();
addAll(c); // 將Collection利用添加元素的方法直接加入鏈表中
}
這兩個構造函數都非常簡單,幾乎沒有什么內容。
添加元素
LinkedList
會通過add()
方法完成最基本的插入操作:
public boolean add(E e) {
linkLast(e);
return true;
}
由上述可以看出,添加一個元素到LinkedList
之中就是將元素添加到這個鏈表的尾部。詳細地探究下linkLast()
方法:
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
這里linkLast()
函數會構建一個新的Node
節點(如果first節點為空,會將這個節點設置成頭節點),并將這個節點設置為last
尾節點。將上一個尾節點的下一個節點設置為新的節點。
除此之外,還有addAll()
函數:
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
Node<E> pred, succ;
if (index == size) {
succ = null;
pred = last;
} else {
succ = node(index);
pred = succ.prev;
}
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
由以上可以看出addAll()
函數會將c轉換成數組,然后找到index
元素的位置,將數組的元素循環添加到尾節點上。
刪除節點
根據索引位置刪除節點的位置:
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
node()
函數是一個查找元素的方法:
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;
}
}
這個函數先判斷索引的位置在前半段還是后半段,然后通prev
或者next
遍歷直到index
的位置。
unlink()
函數則將傳入的節點從鏈表中移除,并將這個元素的前后元素鏈接起來:
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;
}
查詢
LinkedList
查詢特別簡單,就是利用了之前已經看過的node()
方法:
public E get(int index) {
checkElementIndex(index); // 檢查數組是否會越界
return node(index).item;
}
總結
很明顯相比ArrayList
,LinkedList
在增加和刪除的時候,不需要大動干戈,自然會節約很多資源(但依然沒有辦法避免GC),但是在查詢元素上,LinkedList
就會費勁很多,需要遍歷整個鏈表才能找到數據。