想看我更多文章:【張旭童的博客】blog.csdn.net/zxt0601
想來gayhub和我gaygayup:【mcxtzhang的Github主頁】github.com/mcxtzhangjava
本篇是Java集合類解析的第二篇,上一篇[面試必備:ArrayList源碼解析(JDK8)]裏,咱們嘮了ArrayList
,今兒來繼續說LinkedList
.面試中,這兄弟倆也常常會拿來比較。node
它們兩能夠說是List
接口的兩種不一樣的實現,ArrayList
的增刪效率低,可是改查效率高。
而LinkedList
正好相反,增刪因爲不須要移動底層數組數據,其底層是鏈表實現的,只須要修改鏈表節點指針,因此效率較高。
而改和查,都須要先定位到目標節點,因此效率較低。git
開篇前,再說一遍Collection.toArray();
。
這個方法很重要,不論是ArrayList
、LinkedList
在批量add的時候,都會先轉化成數組去作。 由於數組能夠用for循環直接花式遍歷。比較方便 高效github
套路依舊,
本文將從幾個經常使用方法下手,來閱讀LinkedList
的源碼。
按照從構造方法->經常使用API(增、刪、改、查)的順序來閱讀源碼,並會講解閱讀方法中涉及的一些變量的意義。瞭解LinkedList
的特色、適用場景。面試
若是本文中有不正確的結論、說法,請你們提出和我討論,共同進步,謝謝。數組
歸納的說,LinkedList
是線程不安全的,容許元素爲null的雙向鏈表。
其底層數據結構是鏈表,它實現List<E>, Deque<E>, Cloneable, java.io.Serializable
接口,它實現了Deque<E>
,因此它也能夠做爲一個雙端隊列。和ArrayList
比,沒有實現RandomAccess
因此其如下標,隨機訪問元素速度較慢。安全
因其底層數據結構是鏈表,因此可想而知,它的增刪只須要移動指針便可,故時間效率較高。不須要批量擴容,也不須要預留空間,因此空間效率比ArrayList
高。bash
缺點就是須要隨機訪問元素時,時間效率很低,雖然底層在根據下標查詢Node的時候,會根據index判斷目標Node在前半段仍是後半段,而後決定是順序仍是逆序查詢,以提高時間效率。不過隨着n的增大,整體時間效率依然很低。數據結構
當每次增、刪時,都會修改modCount。app
//集合元素數量
transient int size = 0;
//鏈表頭節點
transient Node<E> first;
//鏈表尾節點
transient Node<E> last;
//啥都不幹
public LinkedList() {
}
//調用 public boolean addAll(Collection<? extends E> c) 將集合c全部元素插入鏈表中
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}複製代碼
構造方法基本沒幹啥。
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;
}
}複製代碼
能夠看出,這是一個雙向鏈表。
接上文,先說addAll
//addAll ,在尾部批量增長
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);//以size爲插入下標,插入集合c中全部元素
}
//以index爲插入下標,插入集合c中全部元素
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);//檢查越界 [0,size] 閉區間
Object[] a = c.toArray();//拿到目標集合數組
int numNew = a.length;//新增元素的數量
if (numNew == 0)//若是新增元素數量爲0,則不增長,並返回false
return false;
Node<E> pred, succ; //index節點的前置節點,後置節點
if (index == size) { //在鏈表尾部追加數據
succ = null; //size節點(隊尾)的後置節點必定是null
pred = last;//前置節點是隊尾
} else {
succ = node(index);//取出index節點,做爲後置節點
pred = succ.prev; //前置節點是,index節點的前一個節點
}
//鏈表批量增長,是靠for循環遍歷原數組,依次執行插入節點操做。對比ArrayList是經過System.arraycopy完成批量增長的
for (Object o : a) {//遍歷要添加的節點。
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);//之前置節點 和 元素值e,構建new一個新節點,
if (pred == null) //若是前置節點是空,說明是頭結點
first = newNode;
else//不然 前置節點的後置節點設置問新節點
pred.next = newNode;
pred = newNode;//步進,當前的節點爲前置節點了,爲下次添加節點作準備
}
if (succ == null) {//循環結束後,判斷,若是後置節點是null。 說明此時是在隊尾append的。
last = pred; //則設置尾節點
} else {
pred.next = succ; // 不然是在隊中插入的節點 ,更新前置節點 後置節點
succ.prev = pred; //更新後置節點的前置節點
}
size += numNew; // 修改數量size
modCount++; //修改modCount
return true;
}
//根據index 查詢出Node,
Node<E> node(int index) {
// assert isElementIndex(index);
//經過下標獲取某個node 的時候,(增、查 ),會根據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;
}
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size; //插入時的檢查,下標能夠是size [0,size]
}複製代碼
小結:
//在尾部插入一個節點: add
public boolean add(E e) {
linkLast(e);
return true;
}
//生成新節點 並插入到 鏈表尾部, 更新 last/first 節點。
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++;//修改size
modCount++;//修改modCount
}複製代碼
//在指定下標,index處,插入一個節點
public void add(int index, E element) {
checkPositionIndex(index);//檢查下標是否越界[0,size]
if (index == size)//在尾節點後插入
linkLast(element);
else//在中間插入
linkBefore(element, node(index));
}
//在succ節點前,插入一個新節點e
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
//保存後置節點的前置節點
final Node<E> pred = succ.prev;
//之前置和後置節點和元素值e 構建一個新節點
final Node<E> newNode = new Node<>(pred, e, succ);
//新節點new是原節點succ的前置節點
succ.prev = newNode;
if (pred == null)//若是以前的前置節點是空,說明succ是原頭結點。因此新節點是如今的頭結點
first = newNode;
else//不然構建前置節點的後置節點爲new
pred.next = newNode;
size++;//修改數量
modCount++;//修改modCount
}複製代碼
小結:
//刪:remove目標節點
public E remove(int index) {
checkElementIndex(index);//檢查是否越界 下標[0,size)
return unlink(node(index));//從鏈表上刪除某節點
}
//從鏈表上刪除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++; //修改modCount
return element; //返回取出的元素值
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//下標[0,size)
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}複製代碼
刪除鏈表中的指定節點:
//由於要考慮 null元素,也是分狀況遍歷
public boolean remove(Object o) {
if (o == null) {//若是要刪除的是null節點(從remove和add 裏 能夠看出,容許元素爲null)
//遍歷每一個節點 對比
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
//將節點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) {//前置節點爲null,
first = next;//則首節點爲next
} else {//不然 更新前置節點的後置節點
prev.next = next;
x.prev = null;//記得將要刪除節點的前置節點置null
}
//若是後置節點爲null,說明是尾節點
if (next == null) {
last = prev;
} else {//不然更新 後置節點的前置節點
next.prev = prev;
x.next = null;//記得刪除節點的後置節點爲null
}
//將刪除節點的元素值置null,以便GC
x.item = null;
size--;//修改size
modCount++;//修改modCount
return element;//返回刪除的元素值
}複製代碼
刪也必定會修改modCount。 按下標刪,也是先根據index找到Node,而後去鏈表上unlink掉這個Node。 按元素刪,會先去遍歷鏈表尋找是否有該Node,考慮到容許null值,因此會遍歷兩遍,而後再去unlink它。
public E set(int index, E element) {
checkElementIndex(index); //檢查越界[0,size)
Node<E> x = node(index);//取出對應的Node
E oldVal = x.item;//保存舊值 供返回
x.item = element;//用新值覆蓋舊值
return oldVal;//返回舊值
}複製代碼
改也是先根據index找到Node,而後替換值,改不修改modCount
//根據index查詢節點
public E get(int index) {
checkElementIndex(index);//判斷是否越界 [0,size)
return node(index).item; //調用node()方法 取出 Node節點,
}複製代碼
//根據節點對象,查詢下標
public int indexOf(Object o) {
int index = 0;
if (o == null) {//若是目標對象是null
//遍歷鏈表
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null)
return index;
index++;
}
} else {////遍歷鏈表
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}複製代碼
//從尾至頭遍歷鏈表,找到目標元素值爲o的節點
public int lastIndexOf(Object o) {
int index = size;
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (x.item == null)
return index;
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}複製代碼
查不修改modCount
咱們也順帶看一下toArray()
.畢竟這是個高頻的API
public Object[] toArray() {
//new 一個新數組 而後遍歷鏈表,將每一個元素存在數組裏,返回
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
result[i++] = x.item;
return result;
}複製代碼
LinkedList 是雙向列表。
經過下標獲取某個node 的時候,(add select),會根據index處於前半段仍是後半段 進行一個折半,以提高查詢效率
刪也必定會修改modCount。 按下標刪,也是先根據index找到Node,而後去鏈表上unlink掉這個Node。 按元素刪,會先去遍歷鏈表尋找是否有該Node,若是有,去鏈表上unlink掉這個Node。