一、源碼解析
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
LinkedList 是一個繼承於AbstractSequentialList的雙向鏈表。它也可以被當作堆棧、隊列或雙端隊列進行操作。
LinkedList 實現 List 接口,能對它進行隊列操作。
LinkedList 實現 Deque 接口,即能將LinkedList當作雙端隊列使用。
LinkedList 實現了Cloneable接口,即覆蓋了函數clone(),能克隆。
LinkedList 實現java.io.Serializable接口,這意味着LinkedList支持序列化,能通過序列化去傳輸。
LinkedList 是非同步的。
爲什麼要繼承自AbstractSequentialList ?
AbstractSequentialList 實現了get(int index)、set(int index, E element)、add(int index, E element) 和 remove(int index)這些骨幹性函數。降低了List接口的複雜度。這些接口都是隨機訪問List的,LinkedList是雙向鏈表;既然它繼承於AbstractSequentialList,就相當於已經實現了“get(int index)這些接口”。
此外,我們若需要通過AbstractSequentialList自己實現一個列表,只需要擴展此類,並提供 listIterator() 和 size() 方法的實現即可。若要實現不可修改的列表,則需要實現列表迭代器的 hasNext、next、hasPrevious、previous 和 index 方法即可。
LinkedList的類圖關係:
LinkedList底層的數據結構是基於雙向循環鏈表的,且頭結點中不存放數據,如下:
既然是雙向鏈表,那麼必定存在一種數據結構——我們可以稱之爲節點,節點實例保存業務數據,前一個節點的位置信息和後一個節點位置信息,如下圖所示:
LinkedList中之定義了兩個屬性:
1 private transient Entry<E> header = new Entry<E>(null, null, null);
2 private transient int size = 0;
header是雙向鏈表的頭節點,它是雙向鏈表節點所對應的類Entry的實例。Entry中包含成員變量: previous, next, element。其中,previous是該節點的上一個節點,next是該節點的下一個節點,element是該節點所包含的值。
size是雙向鏈表中節點實例的個數。
首先來了解節點類Entry類的代碼。
1 private static class Entry<E> {
2 E element;
3 Entry<E> next;
4 Entry<E> previous;
5
6 Entry(E element, Entry<E> next, Entry<E> previous) {
7 this.element = element;
8 this.next = next;
9 this.previous = previous;
10 }
11 }
節點類很簡單,element存放業務數據,previous與next分別存放前後節點的信息(在數據結構中我們通常稱之爲前後節點的指針)。
LinkedList的構造方法:
1 public LinkedList() {
2 header.next = header.previous = header;
3 }
4 public LinkedList(Collection<? extends E> c) {
5 this();
6 addAll(c);
7 }
LinkedList提供了兩個構造方法。
第一個構造方法不接受參數,將header實例的previous和next全部指向header實例(注意,這個是一個雙向循環鏈表,如果不是循環鏈表,空鏈表的情況應該是header節點的前一節點和後一節點均爲null),這樣整個鏈表其實就只有header一個節點,用於表示一個空的鏈表。
執行完構造函數後,header實例自身形成一個閉環,如下圖所示:
第二個構造方法接收一個Collection參數c,調用第一個構造方法構造一個空的鏈表,之後通過addAll將c中的元素全部添加到鏈表中。
1 public boolean addAll(Collection<? extends E> c) {
2 return addAll(size, c);
3 }
4 // index參數指定collection中插入的第一個元素的位置
5 public boolean addAll(int index, Collection<? extends E> c) {
6 // 插入位置超過了鏈表的長度或小於0,報IndexOutOfBoundsException異常
7 if (index < 0 || index > size)
8 throw new IndexOutOfBoundsException("Index: "+index+
9 ", Size: "+size);
10 Object[] a = c.toArray();
11 int numNew = a.length;
12 // 若需要插入的節點個數爲0則返回false,表示沒有插入元素
13 if (numNew==0)
14 return false;
15 modCount++;//否則,插入對象,鏈表修改次數加1
16 // 保存index處的節點。插入位置如果是size,則在頭結點前面插入,否則在獲取index處的節點插入
17 Entry<E> successor = (index==size ? header : entry(index));
18 // 獲取前一個節點,插入時需要修改這個節點的next引用
19 Entry<E> predecessor = successor.previous;
20 // 按順序將a數組中的第一個元素插入到index處,將之後的元素插在這個元素後面
21 for (int i=0; i<numNew; i++) {
22 // 結合Entry的構造方法,這條語句是插入操作,相當於C語言中鏈表中插入節點並修改指針
23 Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
24 // 插入節點後將前一節點的next指向當前節點,相當於修改前一節點的next指針
25 predecessor.next = e;
26 // 相當於C語言中成功插入元素後將指針向後移動一個位置以實現循環的功能
27 predecessor = e;
28 }
29 // 插入元素前index處的元素鏈接到插入的Collection的最後一個節點
30 successor.previous = predecessor;
31 // 修改size
32 size += numNew;
33 return true;
34 }
構造方法中的調用了addAll(Collection<? extends E> c)方法,而在addAll(Collection<? extends E> c)方法中僅僅是將size當做index參數調用了addAll(int index,Collection<? extends E> c)方法。
1 private Entry<E> entry(int index) {
2 if (index < 0 || index >= size)
3 throw new IndexOutOfBoundsException("Index: "+index+
4 ", Size: "+size);
5 Entry<E> e = header;
6 // 根據這個判斷決定從哪個方向遍歷這個鏈表
7 if (index < (size >> 1)) {
8 for (int i = 0; i <= index; i++)
9 e = e.next;
10 } else {
11 // 可以通過header節點向前遍歷,說明這個一個循環雙向鏈表,header的previous指向鏈表的最後一個節點,這也驗證了構造方法中對於header節點的前後節點均指向自己的解釋
12 for (int i = size; i > index; i--)
13 e = e.previous;
14 }
15 return e;
16 }
下面說明雙向鏈表添加元素的原理:
添加數據:add()
// 將元素(E)添加到LinkedList中
public boolean add(E e) {
// 將節點(節點數據是e)添加到表頭(header)之前。
// 即,將節點添加到雙向鏈表的末端。
addBefore(e, header);
return true;
}
public void add(int index, E element) {
addBefore(element, (index==size ? header : entry(index)));
}
private Entry<E> addBefore(E e, Entry<E> entry) {
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
newEntry.previous.next = newEntry;
newEntry.next.previous = newEntry;
size++;
modCount++;
return newEntry;
}
addBefore(E e,Entry<E> entry)方法是個私有方法,所以無法在外部程序中調用(當然,這是一般情況,你可以通過反射上面的還是能調用到的)。
addBefore(E e,Entry<E> entry)先通過Entry的構造方法創建e的節點newEntry(包含了將其下一個節點設置爲entry,上一個節點設置爲entry.previous的操作,相當於修改newEntry的“指針”),之後修改插入位置後newEntry的前一節點的next引用和後一節點的previous引用,使鏈表節點間的引用關係保持正確。之後修改和size大小和記錄modCount,然後返回新插入的節點。
下面分解“添加第一個數據”的步驟:
第一步:初始化後LinkedList實例的情況:
第二步:初始化一個預添加的Entry實例(newEntry)。
Entry newEntry = newEntry(e, entry, entry.previous);
第三步:調整新加入節點和頭結點(header)的前後指針。
newEntry.previous.next = newEntry;
newEntry.previous即header,newEntry.previous.next即header的next指向newEntry實例。在上圖中應該是“4號線”指向newEntry。
newEntry.next.previous = newEntry;
newEntry.next即header,newEntry.next.previous即header的previous指向newEntry實例。在上圖中應該是“3號線”指向newEntry。
調整後如下圖所示:
圖——加入第一個節點後LinkedList示意圖
下面分解“添加第二個數據”的步驟:
第一步:新建節點。
圖——添加第二個節點
第二步:調整新節點和頭結點的前後指針信息。
圖——調整前後指針信息
添加後續數據情況和上述一致,LinkedList實例是沒有容量限制的。
總結,addBefore(E e,Entry<E> entry)實現在entry之前插入由e構造的新節點。而add(E e)實現在header節點之前插入由e構造的新節點。爲了便於理解,下面給出插入節點的示意圖。
public void addFirst(E e) {
addBefore(e, header.next);
}
public void addLast(E e) {
addBefore(e, header);
}
看上面的示意圖,結合addBefore(E e,Entry<E> entry)方法,很容易理解addFrist(E e)只需實現在header元素的下一個元素之前插入,即示意圖中的一號之前。addLast(E e)只需在實現在header節點前(因爲是循環鏈表,所以header的前一個節點就是鏈表的最後一個節點)插入節點(插入後在2號節點之後)。
清除數據clear()
1 public void clear() {
2 Entry<E> e = header.next;
3 // e可以理解爲一個移動的“指針”,因爲是循環鏈表,所以回到header的時候說明已經沒有節點了
4 while (e != header) {
5 // 保留e的下一個節點的引用
6 Entry<E> next = e.next;
7 // 解除節點e對前後節點的引用
8 e.next = e.previous = null;
9 // 將節點e的內容置空
10 e.element = null;
11 // 將e移動到下一個節點
12 e = next;
13 }
14 // 將header構造成一個循環鏈表,同構造方法構造一個空的LinkedList
15 header.next = header.previous = header;
16 // 修改size
17 size = 0;
18 modCount++;
19 }
數據包含 contains(Object o)
public boolean contains(Object o) {
return indexOf(o) != -1;
}
// 從前向後查找,返回“值爲對象(o)的節點對應的索引” 不存在就返回-1
public int indexOf(Object o) {
int index = 0;
if (o==null) {
for (Entry e = header.next; e != header; e = e.next) {
if (e.element==null)
return index;
index++;
}
} else {
for (Entry e = header.next; e != header; e = e.next) {
if (o.equals(e.element))
return index;
index++;
}
}
return -1;
}
indexOf(Object o)判斷o鏈表中是否存在節點的element和o相等,若相等則返回該節點在鏈表中的索引位置,若不存在則放回-1。
contains(Object o)方法通過判斷indexOf(Object o)方法返回的值是否是-1來判斷鏈表中是否包含對象o。
幾個remove方法最終都是調用了一個私有方法:remove(Entry<E> e),只是其他簡單邏輯上的區別。下面分析remove(Entry<E> e)方法。
1 private E remove(Entry<E> e) {
2 if (e == header)
3 throw new NoSuchElementException();
4 // 保留將被移除的節點e的內容
5 E result = e.element;
6 // 將前一節點的next引用賦值爲e的下一節點
7 e.previous.next = e.next;
8 // 將e的下一節點的previous賦值爲e的上一節點
9 e.next.previous = e.previous;
10 // 上面兩條語句的執行已經導致了無法在鏈表中訪問到e節點,而下面解除了e節點對前後節點的引用
11 e.next = e.previous = null;
12 // 將被移除的節點的內容設爲null
13 e.element = null;
14 // 修改size大小
15 size--;
16 modCount++;
17 // 返回移除節點e的內容
18 return result;
19 }
由於刪除了某一節點因此調整相應節點的前後指針信息,如下:
e.previous.next = e.next;//預刪除節點的前一節點的後指針指向預刪除節點的後一個節點。
e.next.previous = e.previous;//預刪除節點的後一節點的前指針指向預刪除節點的前一個節點。
清空預刪除節點:
e.next = e.previous = null;
e.element = null;
交給gc完成資源回收,刪除操作結束。
與ArrayList比較而言,LinkedList的刪除動作不需要“移動”很多數據,從而效率更高。
Get(int)方法的實現在remove(int)中已經涉及過了。首先判斷位置信息是否合法(大於等於0,小於當前LinkedList實例的Size),然後遍歷到具體位置,獲得節點的業務數據(element)並返回。
注意:爲了提高效率,需要根據獲取的位置判斷是從頭還是從尾開始遍歷。
// 獲取雙向鏈表中指定位置的節點
private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
// 獲取index處的節點。
// 若index < 雙向鏈表長度的1/2,則從前先後查找;
// 否則,從後向前查找。
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}
注意細節:位運算與直接做除法的區別。先將index與長度size的一半比較,如果index<size/2,就只從位置0往後遍歷到位置index處,而如果index>size/2,就只從位置size往前遍歷到位置index處。這樣可以減少一部分不必要的遍歷
clone()
1 public Object clone() {
2 LinkedList<E> clone = null;
3 try {
4 clone = (LinkedList<E>) super.clone();
5 } catch (CloneNotSupportedException e) {
6 throw new InternalError();
7 }
8 clone.header = new Entry<E>(null, null, null);
9 clone.header.next = clone.header.previous = clone.header;
10 clone.size = 0;
11 clone.modCount = 0;
12 for (Entry<E> e = header.next; e != header; e = e.next)
13 clone.add(e.element);
14 return clone;
15 }
調用父類的clone()方法初始化對象鏈表clone,將clone構造成一個空的雙向循環鏈表,之後將header的下一個節點開始將逐個節點添加到clone中。最後返回克隆的clone對象。
toArray()
1 public Object[] toArray() {
2 Object[] result = new Object[size];
3 int i = 0;
4 for (Entry<E> e = header.next; e != header; e = e.next)
5 result[i++] = e.element;
6 return result;
7 }
創建大小和LinkedList相等的數組result,遍歷鏈表,將每個節點的元素element複製到數組中,返回數組。
toArray(T[] a)
1 public <T> T[] toArray(T[] a) {
2 if (a.length < size)
3 a = (T[])java.lang.reflect.Array.newInstance(
4 a.getClass().getComponentType(), size);
5 int i = 0;
6 Object[] result = a;
7 for (Entry<E> e = header.next; e != header; e = e.next)
8 result[i++] = e.element;
9 if (a.length > size)
10 a[size] = null;
11 return a;
12 }
先判斷出入的數組a的大小是否足夠,若大小不夠則拓展。這裏用到了發射的方法,重新實例化了一個大小爲size的數組。之後將數組a賦值給數組result,遍歷鏈表向result中添加的元素。最後判斷數組a的長度是否大於size,若大於則將size位置的內容設置爲null。返回a。
從代碼中可以看出,數組a的length小於等於size時,a中所有元素被覆蓋,被拓展來的空間存儲的內容都是null;若數組a的length的length大於size,則0至size-1位置的內容被覆蓋,size位置的元素被設置爲null,size之後的元素不變。
爲什麼不直接對數組a進行操作,要將a賦值給result數組之後對result數組進行操作?
LinkedList的Iterator
除了Entry,LinkedList還有一個內部類:ListItr。
ListItr實現了ListIterator接口,可知它是一個迭代器,通過它可以遍歷修改LinkedList。
在LinkedList中提供了獲取ListItr對象的方法:listIterator(int index)。
1 public ListIterator<E> listIterator(int index) {
2 return new ListItr(index);
3 }
該方法只是簡單的返回了一個ListItr對象。
LinkedList中還有通過集成獲得的listIterator()方法,該方法只是調用了listIterator(int index)並且傳入0。
下面詳細分析ListItr。
1 private class ListItr implements ListIterator<E> {
2 // 最近一次返回的節點,也是當前持有的節點
3 private Entry<E> lastReturned = header;
4 // 對下一個元素的引用
5 private Entry<E> next;
6 // 下一個節點的index
7 private int nextIndex;
8 private int expectedModCount = modCount;
9 // 構造方法,接收一個index參數,返回一個ListItr對象
10 ListItr(int index) {
11 // 如果index小於0或大於size,拋出IndexOutOfBoundsException異常
12 if (index < 0 || index > size)
13 throw new IndexOutOfBoundsException("Index: "+index+
14 ", Size: "+size);
15 // 判斷遍歷方向
16 if (index < (size >> 1)) {
17 // next賦值爲第一個節點
18 next = header.next;
19 // 獲取指定位置的節點
20 for (nextIndex=0; nextIndex<index; nextIndex++)
21 next = next.next;
22 } else {
23 // else中的處理和if塊中的處理一致,只是遍歷方向不同
24 next = header;
25 for (nextIndex=size; nextIndex>index; nextIndex--)
26 next = next.previous;
27 }
28 }
29 // 根據nextIndex是否等於size判斷時候還有下一個節點(也可以理解爲是否遍歷完了LinkedList)
30 public boolean hasNext() {
31 return nextIndex != size;
32 }
33 // 獲取下一個元素
34 public E next() {
35 checkForComodification();
36 // 如果nextIndex==size,則已經遍歷完鏈表,即沒有下一個節點了(實際上是有的,因爲是循環鏈表,任何一個節點都會有上一個和下一個節點,這裏的沒有下一個節點只是說所有節點都已經遍歷完了)
37 if (nextIndex == size)
38 throw new NoSuchElementException();
39 // 設置最近一次返回的節點爲next節點
40 lastReturned = next;
41 // 將next“向後移動一位”
42 next = next.next;
43 // index計數加1
44 nextIndex++;
45 // 返回lastReturned的元素
46 return lastReturned.element;
47 }
48
49 public boolean hasPrevious() {
50 return nextIndex != 0;
51 }
52 // 返回上一個節點,和next()方法相似
53 public E previous() {
54 if (nextIndex == 0)
55 throw new NoSuchElementException();
56
57 lastReturned = next = next.previous;
58 nextIndex--;
59 checkForComodification();
60 return lastReturned.element;
61 }
62
63 public int nextIndex() {
64 return nextIndex;
65 }
66
67 public int previousIndex() {
68 return nextIndex-1;
69 }
70 // 移除當前Iterator持有的節點
71 public void remove() {
72 checkForComodification();
73 Entry<E> lastNext = lastReturned.next;
74 try {
75 LinkedList.this.remove(lastReturned);
76 } catch (NoSuchElementException e) {
77 throw new IllegalStateException();
78 }
79 if (next==lastReturned)
80 next = lastNext;
81 else
82 nextIndex--;
83 lastReturned = header;
84 expectedModCount++;
85 }
86 // 修改當前節點的內容
87 public void set(E e) {
88 if (lastReturned == header)
89 throw new IllegalStateException();
90 checkForComodification();
91 lastReturned.element = e;
92 }
93 // 在當前持有節點後面插入新節點
94 public void add(E e) {
95 checkForComodification();
96 // 將最近一次返回節點修改爲header
97 lastReturned = header;
98 addBefore(e, next);
99 nextIndex++;
100 expectedModCount++;
101 }
102 // 判斷expectedModCount和modCount是否一致,以確保通過ListItr的修改操作正確的反映在LinkedList中
103 final void checkForComodification() {
104 if (modCount != expectedModCount)
105 throw new ConcurrentModificationException();
106 }
107 }
下面是一個ListItr的使用實例。
1 LinkedList<String> list = new LinkedList<String>();
2 list.add("First");
3 list.add("Second");
4 list.add("Thrid");
5 System.out.println(list);
6 ListIterator<String> itr = list.listIterator();
7 while (itr.hasNext()) {
8 System.out.println(itr.next());
9 }
10 try {
11 System.out.println(itr.next());// throw Exception
12 } catch (Exception e) {
13 // TODO: handle exception
14 }
15 itr = list.listIterator();
16 System.out.println(list);
17 System.out.println(itr.next());
18 itr.add("new node1");
19 System.out.println(list);
20 itr.add("new node2");
21 System.out.println(list);
22 System.out.println(itr.next());
23 itr.set("modify node");
24 System.out.println(list);
25 itr.remove();
26 System.out.println(list);
1 結果:
2 [First, Second, Thrid]
3 First
4 Second
5 Thrid
6 [First, Second, Thrid]
7 First
8 [First, new node1, Second, Thrid]
9 [First, new node1, new node2, Second, Thrid]
10 Second
11 [First, new node1, new node2, modify node, Thrid]
12 [First, new node1, new node2, Thrid]
LinkedList還有一個提供Iterator的方法:descendingIterator()。該方法返回一個DescendingIterator對象。DescendingIterator是LinkedList的一個內部類。
1 public Iterator<E> descendingIterator() {
2 return new DescendingIterator();
3 }
下面分析詳細分析DescendingIterator類。
1 private class DescendingIterator implements Iterator {
2 // 獲取ListItr對象
3 final ListItr itr = new ListItr(size());
4 // hasNext其實是調用了itr的hasPrevious方法
5 public boolean hasNext() {
6 return itr.hasPrevious();
7 }
8 // next()其實是調用了itr的previous方法
9 public E next() {
10 return itr.previous();
11 }
12 public void remove() {
13 itr.remove();
14 }
15 }
從類名和上面的代碼可以看出這是一個反向的Iterator,代碼很簡單,都是調用的ListItr類中的方法。