好久前咱們已經學習了ArrayList和HashMap的源碼,有興趣的同窗請移步:深刻剖析ArrayList源碼
深刻剖析HashMap源碼
今天咱們來談談LinkedList源碼。java
LinkedList是用鏈表實現的List,是一個雙向鏈表。node
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable{//底層是雙向鏈表 //元素數量 transient int size = 0; //第一個結點 transient Node<E> first; //最後一個結點 transient Node<E> last; }
咱們還看到了LinkedList實現了Deque接口,所以,咱們能夠操做LinkedList像操做隊列和棧同樣。segmentfault
LinkedList底層維護着一個Node組成的鏈表,在源碼中,是以下圖的一個靜態內部類:數組
//內部類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; }
在看添加刪除等方法前咱們先去了解LinkedList實現的一些操做鏈表的輔助函數,看了這幾個函數後再去看別的方法會容易不少。函數
插入元素到頭部
void linkFirst(E e) { final Node<E> f = first; final Node<E> newNode = new Node<>(null, e, f);//設置newNode的前結點爲null,後結點爲f first = newNode; if (f == null)//首先連接元素,同時把newNode設爲最後一個結點 last = newNode; else f.prev = newNode; size++; modCount++; }
插入元素到尾部
void linkLast(E e) { final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null);//設置newNode的前結點爲l,後結點爲null last = newNode;//新結點變成最後一個結點 //若l == null說明是首次連接元素,將first也指向新結點 if (l == null) first = newNode; else l.next = newNode; size++; modCount++;//修改次數+1 }
在給定結點前插入元素e
void linkBefore(E e, Node<E> succ) { final Node<E> pred = succ.prev; final Node<E> newNode = new Node<>(pred, e, succ);//設置newNode的前結點爲pred,後結點爲succ succ.prev = newNode; if (pred == null)//若是succ是頭結點,將newNode設置爲頭結點 first = newNode; else pred.next = newNode; size++; modCount++; }
刪除鏈表結點
E unlink(Node<E> x) { 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;//GC回收 } //判斷是不是尾結點 if (next == null) { last = prev; } else { next.prev = prev; x.next = null;//GC回收 } x.item = null;//GC回收 size--; modCount++; return element; }
返回指定位置的結點
Node<E> node(int index) { //根據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; } }
public LinkedList() {} //構造一個包含指定集合元素的LinkenList public LinkedList(Collection<? extends E> c) { this(); addAll(c); }
很簡單,這裏跳過。學習
add方法
/* * 添加元素到末尾 */ public boolean add(E e) { linkLast(e);//插入到鏈表尾部 return true; } /* * 添加元素到指定位置 */ public void add(int index, E element) { checkPositionIndex(index); //參數校驗 ——> index >= 0 && index <= size if (index == size) linkLast(element);//插入到鏈表尾部 else linkBefore(element, node(index));//插入到指定結點前面 } /** * 將指定集合中的元素插入到鏈表中 * addAll(Collection<? extends E> c)——>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; if (index == size) {//插入元素到尾部 succ = null; pred = last; } else {//在index位置插入 succ = node(index); pred = succ.prev; } //依次從集合中取出元素插入到鏈表 for (Object o : a) { E e = (E) o; Node<E> newNode = new Node<>(pred, e, null);//設置newNode的前結點爲pred,後結點爲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; } //addFirst、addLast省略.....
get/set方法
/* * 返回指定位置元素 */ public E get(int index) { checkElementIndex(index); return node(index).item; } /* * 設置元素 */ public E set(int index, E element) { checkElementIndex(index); Node<E> x = node(index); E oldVal = x.item; x.item = element; return oldVal; }
peek/poll方法
/* * 返回頭結點值,若是鏈表爲空則返回null */ public E peek() { final Node<E> f = first; return (f == null) ? null : f.item; } /* * 刪除頭結點並返回頭結點值,若是鏈表爲空則返回null */ public E poll() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); }
remove方法
/* * 默認刪除頭結點 */ public E remove() { return removeFirst(); } /* * 刪除指定位置結點 */ public E remove(int index) { checkElementIndex(index); return unlink(node(index)); } /* * 刪除指定結點 */ public boolean remove(Object o) { if (o == 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; }
indexOf/lastIndexOf方法
/* * 返回指定對象在鏈表中的索引(若是沒有則返回-1) * lastIndexOf同理(其實就是從後向前遍歷) */ 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; }
toArray方法
/* * 將鏈表包裝成數組返回 */ public Object[] toArray() { Object[] result = new Object[size]; int i = 0; //依次取出結點值放入數組 for (Node<E> x = first; x != null; x = x.next) result[i++] = x.item; return result; } /* * 將鏈表包裝成指定類型數組返回 */ public <T> T[] toArray(T[] a) { if (a.length < size)//給點的數組長度小於鏈表長度 //建立一個類型與a同樣,長度爲size的數組 a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size); int i = 0; Object[] result = a;//定義result指向給定數組,修改result == 修改a //依次把結點值放入result數組 for (Node<E> x = first; x != null; x = x.next) result[i++] = x.item; if (a.length > size) a[size] = null; return a; }
listIterator方法
ListIterator是一個功能更增強大的接口, ListIterator在Iterator基礎上提供了add、set、previous等對列表的操做。ui
public ListIterator<E> listIterator(int index) { checkPositionIndex(index);//參數校驗 return new ListItr(index); } ListItr是一個內部類 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);//index默認爲0 nextIndex = index; } /*判斷是否有下一個元素*/ public boolean hasNext() { return nextIndex < size; } /*向後遍歷,返回越過的元素*/ public E next() { checkForComodification();//fail-fast if (!hasNext()) throw new NoSuchElementException(); lastReturned = next; next = next.next; nextIndex++; return lastReturned.item; } /*判斷是否有上一個元素*/ public boolean hasPrevious() { return nextIndex > 0; } /*向前遍歷,返回越過的元素*/ public E previous() { checkForComodification();//fail-fast if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = next = (next == null) ? last : next.prev;//調用previous後lastReturned = next nextIndex--; return lastReturned.item; } /*返回下一個越過的元素索引*/ public int nextIndex() { return nextIndex; } /*返回上一個越過的元素索引*/ public int previousIndex() { return nextIndex - 1; } /*刪除元素*/ public void remove() { checkForComodification();//fail-fast if (lastReturned == null) throw new IllegalStateException(); Node<E> lastNext = lastReturned.next; unlink(lastReturned);//從鏈表中刪除lastReturned,modCount++(該方法會幫你處理結點指針指向) if (next == lastReturned)//調用previous後next == lastReturned next = lastNext; else nextIndex--; lastReturned = null;//GC expectedModCount++; } /*設置元素*/ public void set(E e) { if (lastReturned == null) throw new IllegalStateException(); checkForComodification();//fail-fast lastReturned.item = e; } /*插入元素*/ public void add(E e) { checkForComodification();//fail-fast lastReturned = null; if (next == null) linkLast(e); else linkBefore(e, next); nextIndex++; expectedModCount++; } /*操做未遍歷的元素*/ 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(); } /*fail-fast*/ final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
還有不少關於LinkedList的方法這裏就不一一列舉了,總的來講若是鏈表學得好的話看懂源碼仍是沒問題的,今天就學到這裏,若是錯誤請多指教。this