Collection原始碼之路(2)——LinkedList
阿新 • • 發佈:2018-11-10
上篇文章Collection原始碼之路(1)——ArrayList我們提到ArrayList其實就是可變長的陣列,我們都知道資料物理結構包括順序儲存和鏈式儲存兩種,特點是
順序儲存方便查詢,修改比較麻煩
鏈式儲存修改方便,查詢比較麻煩
ArrayList採用陣列的儲存結構,如果資料量很大的時候做增加或者刪除操作都是比較耗時的,故此我們使用鏈式儲存結構打造一個方便增加和刪除的集合——LinkedList
首先先來看下“雙鏈表”的構成
Node結點具有兩個指標,pre指標指向上一個結點,next指標指向後一個結點,item存放的是資料,為什麼要提到雙鏈表?因為LinkedList底層就是用的雙鏈表,這樣查詢的時候可以選擇從前往後查還是從後往前查,結點之間連線更加緊密。
接著我們看下LinkedList成員
transient int size = 0;
//集合長度,transient 之前ArrayList解釋過,不再解釋
/**
* Pointer to first node.
*/
transient Node<E> first; //指向第一個結點
/**
* Pointer to last node.
*/
transient Node<E> last;//指向最後一個結點
//定義一個結點,帶有前後兩個指標,對於外界來說只知道有資料並不知道有指標
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;
}
}
add(E e)方法
public boolean add(E e) {
linkLast(e);
return true;
}
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++;
}
get(int index)方法
public E get(int index) {
checkElementIndex(index);//檢查下標是否越界
return node(index).item;
}
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;
}
}
node(int index)這裡就利用了前後指標的方便,如果index小於總長度一半,那麼就從前往後查詢,如果大於一半就從後往前查詢
remove(int index)
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
//刪除該結點,同時避免該結點是頭尾結點做些處理
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;
}
clear()
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
for (Node<E> x = first; x != null; ) {
Node<E> next = x.next;
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
first = last = null;
size = 0;
modCount++;
}
和ArrayList不同,刪除不可以靠索引刪除,只能指標迴圈判斷
LinkedList與此同時也實現了Deque介面,裡面的方法我不在這裡講,後面降到Deque的時候再細說
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
整體來看,LinkedList還是很簡單的,其實就是一個雙鏈表,僅此而已。