目錄javascript
java.util.LinkedList 繼承了 AbstractSequentialList 並實現了List , Deque , Cloneable 接口,以及Serializable 接口html
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable {}
類之間的繼承體系以下:java
下面就對繼承樹中的部分節點進行大體介紹:node
AbstractSequentialList 介紹:
這個接口是List一系列子類接口的核心接口,以求最大限度的減小實現此接口的工做量,由順序訪問數據存儲(例如連接鏈表)支持。對於隨機訪問的數據(像是數組),AbstractList 應該優先被使用這個接口能夠說是與AbstractList類相反的,它實現了隨機訪問方法,提供了get(int index),set(int index,E element), add(int index,E element) and remove(int index)方法程序員對於程序員來講:數組
要實現一個列表,程序員只須要擴展這個類而且提供listIterator 和 size方法便可。
對於不可修改的列表來講, 程序員須要實現列表迭代器的 hasNext(), next(), hasPrevious(),
previous 和 index 方法安全
AbstractList 介紹:併發
這個接口也是List繼承類層次的核心接口,以求最大限度的減小實現此接口的工做量,由順序訪問
數據存儲(例如連接鏈表)支持。對於順序訪問的數據(像是鏈表),AbstractSequentialList 應該優先被使用,
若是須要實現不可修改的list,程序員須要擴展這個類,list須要實現get(int) 方法和List.size()方法
若是須要實現可修改的list,程序員必須額外重寫set(int,Object) set(int,E)方法(不然會拋出
UnsupportedOperationException的異常),若是list是可變大小的,程序員必須額外重寫add(int,Object) , add(int, E) and remove(int) 方法函數
AbstractCollection 介紹:源碼分析
這個接口是Collection接口的一個核心實現,儘可能減小實現此接口所需的工做量
爲了實現不可修改的collection,程序員應該繼承這個類並提供呢iterator和size 方法
爲了實現可修改的collection,程序團須要額外重寫類的add方法,iterator方法返回的Iterator迭代器也必須實現remove方法
上面看完了LinkedList 的繼承體系以後,來看看LinkedList的基本方法說明
添加 add(): ----> 1. add(E e) : 直接在'末尾'處添加元素 ----> 2. add(int index,E element) : 在'指定索引處添'加元素 ----> 3. addAll(Collections<? extends E> c) : 在'末尾'處添加一個collection集合 ----> 4. addAll(int index,Collections<? extends E> c):在'指定位置'添加一個collection集合 ----> 5. addFirst(E e): 在'頭部'添加指定元素 ----> 6. addLast(E e): 在'尾部'添加指定元素 offer(): ----> 1. offer(E e): 在鏈表'末尾'添加元素 ----> 2. offerFirst(E e): 在'鏈表頭'添加指定元素 ----> 3. offerLast(E e): 在'鏈表尾'添加指定元素 push(E e): 在'頭部'壓入元素 移除 poll(): ----> 1. poll(): 訪問並移除'首部'元素 ----> 2. pollFirst(): 訪問並移除'首部'元素 ----> 3. pollLast(): 訪問並移除'尾部'元素 pop(): 從列表表明的堆棧中彈出元素,從'頭部'彈出 remove(): ----> 1. remove(): 移除並返回'首部'元素 ----> 2. remove(int index) : 移除'指定索引'處的元素 ----> 3. remove(Object o): 移除指定元素 ----> 4. removeFirst(): 移除並返回'第一個'元素 ----> 5. removeFirstOccurrence(Object o): 從頭至尾遍歷,移除'第一次'出現的元素 ----> 6. removeLast(): 移除並返回'最後一個'元素 ----> 7. removeLastOccurrence(Object o): 從頭至尾遍歷,移除'最後一次'出現的元素 clear(): 清空全部元素 訪問 peek(): ----> 1. peek(): 只訪問,不移除'首部'元素 ----> 2. peekFirst(): 只訪問,不移除'首部'元素,若是鏈表不包含任何元素,則返回null ----> 3. peekLast(): 只訪問,不移除'尾部'元素,若是鏈表不包含任何元素,返回null element(): 只訪問,不移除'頭部'元素 get(): ----> 1. get(int index): 返回'指定索引'處的元素 ----> 2. getFirst(): 返回'第一個'元素 ----> 3. getLast(): 返回'最後一個'元素 indexOf(Object o): 檢索某個元素'第一次'出現所在的位置 LastIndexOf(Object o): 檢索某個元素'最後一次'出現的位置 其餘 clone() : 返回一個鏈表的拷貝,返回值爲Object 類型 contains(Object o): 判斷鏈表是否包含某個元素 descendingIterator(): 返回一個迭代器,裏面的元素是倒敘返回的 listIterator(int index) : 在指定索引處建立一個'雙向遍歷迭代器' set(int index, E element): 替換某個位置處的元素 size() : 返回鏈表的長度 spliterator(): 建立一個後期綁定並快速失敗的元素 toArray(): 將鏈表轉變爲數組返回
學以至用,熟悉了上面基本方法以後,來簡單作一個demo測試一下上面的方法:
/** * 此方法描述 * LinedList 集合的基本使用 */ public class LinkedListTest { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("111"); list.add("222"); list.add("333"); list.add(1,"123"); // 分別在頭部和尾部添加元素 list.addFirst("top"); list.addLast("bottom"); System.out.println(list); // 數組克隆 Object listClone = list.clone(); System.out.println(listClone); // 建立一個首尾互換的迭代器 Iterator<String> it = list.descendingIterator(); while (it.hasNext()){ System.out.print(it.next() + " "); } System.out.println(); list.clear(); System.out.println("list.contains('111') ? " + list.contains("111")); Collection<String> collec = Arrays.asList("123","213","321"); list.addAll(collec); System.out.println(list); System.out.println("list.element = " + list.element()); System.out.println("list.get(2) = " + list.get(2)); System.out.println("list.getFirst() = " + list.getFirst()); System.out.println("list.getLast() = " + list.getLast()); // 檢索指定元素出現的位置 System.out.println("list.indexOf(213) = " + list.indexOf("213")); list.add("123"); System.out.println("list.lastIndexOf(123) = " + list.lastIndexOf("123")); // 在首部和尾部添加元素 list.offerFirst("first"); list.offerLast("999"); System.out.println("list = " + list); list.offer("last"); // 只訪問,不移除指定元素 System.out.println("list.peek() = " + list.peek()); System.out.println("list.peekFirst() = " + list.peekFirst()); System.out.println("list.peekLast() = " + list.peekLast()); // 訪問並移除元素 System.out.println("list.poll() = " + list.poll()); System.out.println("list.pollFirst() = " + list.pollFirst()); System.out.println("list.pollLast() = " + list.pollLast()); System.out.println("list = " + list); // 從首部彈出元素 list.pop(); // 壓入元素 list.push("123"); System.out.println("list.size() = " + list.size()); System.out.println("list = " + list); // remove操做 System.out.println(list.remove()); System.out.println(list.remove(1)); System.out.println(list.remove("999")); System.out.println(list.removeFirst()); System.out.println("list = " + list); list.addAll(collec); list.addFirst("123"); list.addLast("123"); System.out.println("list = " + list); list.removeFirstOccurrence("123"); list.removeLastOccurrence("123"); list.removeLast(); System.out.println("list = " + list); list.addFirst("top"); list.addLast("bottom"); list.set(2,"321"); System.out.println("list = " + list); System.out.println("--------------------------"); // 建立一個list的雙向鏈表 ListIterator<String> listIterator = list.listIterator(); while(listIterator.hasNext()){ // 移到list的末端 System.out.println(listIterator.next()); } System.out.println("--------------------------"); while (listIterator.hasPrevious()){ // 移到list的首端 System.out.println(listIterator.previous()); } } }
Console:
-------1------- [top, 111, 123, 222, 333, bottom] -------2-------[top, 111, 123, 222, 333, bottom] bottom 333 222 123 111 top list.contains('111') ? false [123, 213, 321] list.element = 123 list.get(2) = 321 list.getFirst() = 123 list.getLast() = 321 list.indexOf(213) = 1 list.lastIndexOf(123) = 3 -------4------- [first, 123, 213, 321, 123, 999] list.peek() = first list.peekFirst() = first list.peekLast() = last list.poll() = first list.pollFirst() = 123 list.pollLast() = last -------5------- [213, 321, 123, 999] list.size() = 4 -------6------- [123, 321, 123, 999] 123 123 true 321 -------7------- [] -------8------- [123, 123, 213, 321, 123] list = [123, 213] -------9------- [top, 123, 321, bottom] -------------------------- top 123 321 bottom -------------------------- bottom 321 123 top
每個鏈表都是一個Node節點,由三個元素組成
private static class Node<E> { // Node節點的元素 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; } }
first 節點也是頭節點, last節點也是尾節點
transient int size = 0; // 鏈表的容量 transient Node<E> first; // 指向第一個節點 transient Node<E> last; // 指向最後一個節點
/** * 空構造函數 */ public LinkedList() {} /** * 建立一個包含指定元素的構造函數 */ public LinkedList(Collection<? extends E> c) { this(); addAll(c); }
前言: 此源碼是做者根據上面的代碼示例一步一步跟進去的,若是有哪些疑問或者講的不正確的地方,請與做者聯繫。
添加
添加的具體流程示意圖:
包括方法有:
add(E e)
add(int index, E element)
addAll(Collection<? extends E> c)
addAll(int index, Collection<? extends E> c)
addFirst(E e)
addLast(E e)
offer(E e)
offerFirst(E e)
offerLast(E e)
下面對這些方法逐個分析其源碼:
add(E e) :
// 添加指定元素至list末尾 public boolean add(E e) { linkLast(e); return true; } // 真正添加節點的操做 void linkLast(E e) { final Node<E> l = last; // 生成一個Node節點 final Node<E> newNode = new Node<>(l, e, null); last = newNode; // 若是l = null,表明的是第一個節點,因此這個節點便是頭節點 // 又是尾節點 if (l == null) first = newNode; else // 若是不是的話,那麼就讓該節點的next 指向新的節點 l.next = newNode; size++; modCount++; }
- 好比第一次添加的是111,此時鏈表中尚未節點,因此此時的尾節點last 爲null, 生成新的節點,因此 此時的尾節點也就是111,因此這個 111 也是頭節點,再進行擴容,修改次數對應增長
- 第二次添加的是 222, 此時鏈表中已經有了一個節點,新添加的節點會添加到尾部,剛剛添加的111 就看成頭節點來使用,222被添加到111的節點後面。
add(int index,E e) :
/** *在指定位置插入指定的元素 */ public void add(int index, E element) { // 下標檢查 checkPositionIndex(index); if (index == size) // 若是須要插入的位置和鏈表的長度相同,就在鏈表的最後添加 linkLast(element); else // 不然就連接在此位置的前面 linkBefore(element, node(index)); } // 越界檢查 private void checkPositionIndex(int index) { if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } // 判斷參數是不是有效位置(對於迭代或者添加操做來講) private boolean isPositionIndex(int index) { return index >= 0 && index <= size; } // linkLast 上面已經介紹過 // 查找索引所在的節點 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; } } // 在非空節點插入元素 void linkBefore(E e, Node<E> succ) { // assert succ != null; // succ 便是插入位置的節點 // 查找該位置處的前面一個節點 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++; }
- 例如在位置爲1處添加值爲123 的元素,首先對下標進行越界檢查,判斷這個位置是否等於鏈表的長度,若是與鏈表長度相同,就往最後插入,若是不一樣的話,就在索引的前面插入。
- 下標爲1 處並不等於索引的長度,因此在索引前面插入,首先對查找 1 這個位置的節點是哪一個,並獲取這個節點的前面一個節點,在判斷這個位置的前一個節點是否爲null,若是是null,那麼這個此處位置的元素就被看成頭節點,若是不是的話,頭節點的next 節點就指向123
addFirst(E e) :
// 在頭節點插入元素 public void addFirst(E e) { linkFirst(e); } private void linkFirst(E e) { // 先找到first 節點 final Node<E> f = first; final Node<E> newNode = new Node<>(null, e, f); first = newNode; if (f == null) // f 爲null,也就表明着沒有頭節點 last = newNode; else f.prev = newNode; size++; modCount++; }
例如要添加top 元素至鏈表的首部,須要先找到first節點,若是first節點爲null,也就說明沒有頭節點,若是不爲null,則頭節點的prev節點是新插入的節點。
addLast(E e) :
public void addLast(E e) { linkLast(e); } // 連接末尾處的節點 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++; }
方法邏輯與在頭節點插入基本相同
addAll(Collections<? extends E> c) :
/** * 在鏈表中批量添加數據 */ public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } 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; // 直接在末尾添加,因此index = size 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; }
Collection<String> collec = Arrays.asList("123","213","321"); list.addAll(collec);
- 例如要插入一個Collection爲123,213,321 的集合,沒有指定插入元素的位置,默認是向鏈表的尾部進行連接,首先會進行數組越界檢查,而後會把集合轉換爲數組,在判斷數組的大小是否爲0,爲0返回,不爲0,繼續下面操做
- 由於是直接向鏈尾插入,因此index = size,而後遍歷每一個數組,首先生成對應的節點,在對節點進行連接,由於succ 是null,此時last 節點 = pred,這個時候的pred節點就是遍歷數組完成後的最後一個節點
- 而後再擴容數組,增長修改次數
addAll(Collections<? extends E> c) : 這個方法的源碼同上
offer也是對元素進行添加操做,源碼和add方法相同
offerFirst(E e)和addFirst(E e) 源碼相同
offerLast(E e)和addLast(E e) 源碼相同)
push(E e) 和addFirst(E e) 源碼相同
取出元素
包括方法有:
peek()
/** * 只是訪問,可是不移除鏈表的頭元素 */ public E peek() { final Node<E> f = first; return (f == null) ? null : f.item; }
peek() 源碼比較簡單,直接找到鏈表的第一個節點,判斷是否爲null,若是爲null,返回null,不然返回鏈首的元素
peekFirst() : 源碼和peek() 相同
peekLast():
/** * 訪問,可是不移除鏈表中的最後一個元素 * 或者返回null若是鏈表是空鏈表 */ public E peekLast() { final Node<E> l = last; return (l == null) ? null : l.item; }
源碼也比較好理解
element() :
/** * 只是訪問,可是不移除鏈表的第一個元素 */ public E element() { return getFirst(); } public E getFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return f.item; }
與peek()相同的地方都是訪問鏈表的第一個元素,不一樣是element元素在鏈表爲null的時候會報空指針異常
****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; } }
get(int index)源碼也是比較好理解,首先對下標進行越界檢查,沒有越界的話直接找到索引位置對應的node節點,進行返回
getFirst() :源碼和element()相同
getLast(): 直接找到最後一個元素進行返回,和getFist幾乎相同
indexOf(Object o) :
/* * 返回第一次出現指定元素的位置,或者-1若是不包含指定元素。 */ public int indexOf(Object o) { int index = 0; if (o == 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; }
兩種狀況:
- 若是須要檢索的元素是null,對元素鏈表進行遍歷,返回x的元素爲空的位置
- 若是須要檢索的元素不是null,對元素的鏈表遍歷,直到找到相同的元素,返回元素下標
lastIndexOf(Object o) :
/* * 返回最後一次出現指定元素的位置,或者-1若是不包含指定元素。 */ 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; }
從IndexOf(Object o)源碼反向理解
刪除
刪除節點的示意圖以下:
包括的方法有:
poll() :
/* * 訪問並移除鏈表中指定元素 */ public E poll() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); } // 斷開第一個非空節點 private E unlinkFirst(Node<E> f) { // assert f == first && f != null; final E element = f.item; final Node<E> next = f.next; f.item = null; f.next = null; // help GC first = next; if (next == null) last = null; else next.prev = null; size--; modCount++; return element; }
poll()方法也比較簡單直接,首先經過Node方法找到第一個鏈表頭,而後把鏈表的元素和鏈表頭指向的next元素置空,再把next節點的元素變爲頭節點的元素
pollFirst() : 與poll() 源碼相同
pollLast(): 與poll() 源碼很類似,再也不解釋
pop()
/* * 彈出鏈表的指定元素,換句話說,移除並返回鏈表中第一個元素 */ public E removeFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(f); } // unlinkFirst 源碼上面👆有
removeFirst源碼就多了若是首部元素爲null,就直接拋出異常的操做
remove(int index):
/* * 移除鏈表指定位置的元素 */ public E remove(int index) { checkElementIndex(index); // 找到index 的節點,斷開指定節點 return unlink(node(index)); } // 斷開指定節點 E unlink(Node<E> x) { // 找到連接節點的元素,next節點和prev節點 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; }
remove(Object o)
/* * 移除列表中第一次出現的指定元素,若是存在的話。若是列表不包含指定元素,則不會改變, * 更進一步來講,移除索引最小的元素,前提是(o == null ? get(i) == null : o.equals(get(i))) */ public boolean remove(Object o) { // 若是o爲null if (o == null) { for (Node<E> x = first; x != null; x = x.next) { // 匹配null對象,刪除控對象,返回true if (x.item == null) { unlink(x); return true; } } } else { // 若是不爲null for (Node<E> x = first; x != null; x = x.next) { // 匹配對應節點,返回true if (o.equals(x.item)) { unlink(x); return true; } } } return false; }
removeFirst() 和remove() 源碼相同
removeFirstOccurrence(Object o)和 remove(Object o) 源碼相同
removeLast() 和 pollLast() 相同
removeLastOccurrence(Object o) 和 removeFirstOccurrence(Object o) 類似
clear()
/* * 清空全部元素 */ public void clear() { // 遍歷元素,把元素的值置爲null 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++; }
clear()方法,先找到鏈表頭,循環遍歷每一項,把每一項的prev,item,next屬性置空,最後再清除first和last節點,注意源碼有一點,x = next ,這行代碼是向後遍歷的意思,根據next的元素再繼續向後查找
其餘方法
鏈表最經常使用的方法就是添加、查找、刪除,下面來介紹一下其餘的方法
clone()
/* * 鏈表複製 */ public Object clone() { // 此處的clone LinkedList<E> clone = superClone(); // Put clone into "virgin" state clone.first = clone.last = null; clone.size = 0; clone.modCount = 0; // Initialize clone with our elements for (Node<E> x = first; x != null; x = x.next) clone.add(x.item); return clone; } private LinkedList<E> superClone() { try { return (LinkedList<E>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e); } } // 本地方法 protected native Object clone() throws CloneNotSupportedException;
clone() 方法調用superClone()可以獲取拷貝事後的值,可是爲何要把first和last置爲null,debug的時候就發現clone對象全部的值都爲null了,並且爲何又要循環遍歷鏈表再添加一遍?
contains(Object o) : 和index源碼幾乎相同
set(int index, E element)
/* * 在指定位置替換指定元素 */ public E set(int index, E element) { // 越界檢查 checkElementIndex(index); // 找到索引元素所在的位置 Node<E> x = node(index); // 元素替換操做,返回替換以前的元素 E oldVal = x.item; x.item = element; return oldVal; }
descendingIterator()
public Iterator<E> descendingIterator() { return new DescendingIterator(); } private class DescendingIterator implements Iterator<E> { private final ListItr itr = new ListItr(size()); public boolean hasNext() { return itr.hasPrevious(); } public E next() { return itr.previous(); } public void remove() { itr.remove(); } }
descendingIterator 就至關於建立了一個倒置的Iterator,倒敘遍歷
listIterator(int index) :
/* * 在指定位置上返回一個列表的迭代器,這個list-Iterator是有快速失敗機制的 * 能夠參見個人另外一篇文章 ArrayList 源碼解析 */ public ListIterator<E> listIterator(int index) { checkPositionIndex(index); return new ListItr(index); } // ListItr 是LinkedList的一個內部類 private class ListItr implements ListIterator<E> { // 上一個被返回的節點 private Node<E> lastReturned; // 下一個節點 private Node<E> next; // 下一個下標 private int nextIndex; // 指望的修改次數 = 修改次數,用於判斷併發狀況 private int expectedModCount = modCount; // 在指定位置建立一個迭代器 ListItr(int index) { next = (index == size) ? null : node(index); nextIndex = index; } // 判斷是否有下一個元素 // 判斷的標準是下一個索引的值 < size ,說明當前位置最大 = 鏈表的容量 public boolean hasNext() { return nextIndex < size; } // 查找下一個元素 public E next() { checkForComodification(); if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; // 指向下一個元素 next = next.next; nextIndex++; return lastReturned.item; } // 是否有以前的元素 public boolean hasPrevious() { // 經過元素索引是否等於0,來判斷是否達到開頭。 return nextIndex > 0; } // 遍歷以前的元素 public E previous() { checkForComodification(); if (!hasPrevious()) throw new NoSuchElementException(); // next指向鏈表的上一個元素 lastReturned = next = (next == null) ? last : next.prev; nextIndex--; return lastReturned.item; } // 下一個索引 public int nextIndex() { return nextIndex; } // 上一個索引 public int previousIndex() { return nextIndex - 1; } // 移除元素,有fail-fast機制 public void remove() { checkForComodification(); if (lastReturned == null) throw new IllegalStateException(); Node<E> lastNext = lastReturned.next; unlink(lastReturned); if (next == lastReturned) next = lastNext; else nextIndex--; lastReturned = null; expectedModCount++; } // 設置當前節點爲e,有fail-fast機制 public void set(E e) { if (lastReturned == null) throw new IllegalStateException(); checkForComodification(); lastReturned.item = e; } // 將e添加到當前節點的前面,也有fail-fast機制 public void add(E e) { checkForComodification(); lastReturned = null; if (next == null) linkLast(e); else linkBefore(e, next); nextIndex++; expectedModCount++; } // jdk1.8引入,用於快速遍歷鏈表元素 public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (modCount == expectedModCount && nextIndex < size) { action.accept(next.item); lastReturned = next; next = next.next; nextIndex++; } checkForComodification(); } // 判斷 「modCount和expectedModCount是否相等」,依次來實現fail-fast機制 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
toArray()
/* * 返回LinkedList的Object[]數組 */ public Object[] toArray() { Object[] result = new Object[size]; int i = 0; //將鏈表中全部節點的數據都添加到Object[]數組中 for (Node<E> x = first; x != null; x = x.next) result[i++] = x.item; return result; }
toArray(T[] a)
/* * 返回LinkedList的模板數組。所謂模板數組,便可以將T設爲任意的數據類型 */ public <T> T[] toArray(T[] a) { // 若數組a的大小 < LinkedList的元素個數(意味着數組a不能容納LinkedList中所有元素) // 則新建一個T[]數組,T[]的大小爲LinkedList大小,並將該T[]賦值給a。 if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); //將鏈表中全部節點的數據都添加到數組a中 int i = 0; Object[] result = a; for (Node<E> x = first; x != null; x = x.next) result[i++] = x.item; if (a.length > size) a[size] = null; return a; }
後記 : 筆者才疏學淺,若是有哪處錯誤產生誤導,請及時與筆者聯繫更正,一塊兒共建積極向上的it氛圍
文章參考: