文章的內容基於JDK1.7進行分析,之因此選用這個版本,是由於1.8的有些類作了改動,增長了閱讀的難度,雖然是1.7,可是對於1.8作了重大改動的內容,文章也會進行說明。java
LinkedList類是List接口的實現類,它是一個集合,能夠根據索引來隨機的訪問集合中的元素,還實現了Deque接口,它仍是一個隊列,能夠被當成雙端隊列來使用。雖然LinkedList是一個List集合,可是它的實現方式和ArrayList是徹底不一樣的,ArrayList的底層是經過一個動態的Object[]數組來實現的,而LinkedList的底層是經過鏈表來實現的,所以它的隨機訪問速度是比較差的,可是它的刪除,插入操做會很快。node
java.lang.Object java.util.AbstractCollection<E> java.util.AbstractList<E> java.util.AbstractSequentialList<E> java.util.LinkedList<E>
Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E>, Queue<E>
transient int size = 0; //LinkedList中存放的元素個數 transient Node<E> first; //頭節點 transient Node<E> last; //尾節點
什麼是鏈表
鏈表是由一系列非連續的節點組成的存儲結構,簡單分下類的話,鏈表又分爲單向鏈表和雙向鏈表,而單向/雙向鏈表又能夠分爲循環鏈表和非循環鏈表,下面簡單就這四種鏈表進行圖解說明。數組
1.單向鏈表
單向鏈表就是經過每一個結點的指針指向下一個結點從而連接起來的結構,最後一個節點的next指向null。安全
2.單向循環鏈表
單向循環鏈表和單向列表的不一樣是,最後一個節點的next不是指向null,而是指向head節點,造成一個「環」。數據結構
3.雙向鏈表
從名字就能夠看出,雙向鏈表是包含兩個指針的,pre指向前一個節點,next指向後一個節點,可是第一個節點head的pre指向null,最後一個節點的tail指向null。ide
4.雙向循環鏈表
雙向循環鏈表和雙向鏈表的不一樣在於,第一個節點的pre指向最後一個節點,最後一個節點的next指向第一個節點,也造成一個「環」。而LinkedList就是基於雙向循環鏈表設計的。性能
LinkedList是經過雙向鏈表去實現的,既然是鏈表實現那麼它的隨機訪問效率比ArrayList要低,順序訪問的效率要比較的高。每一個節點都有一個前驅(以前前面節點的指針)和一個後繼(指向後面節點的指針),效果以下圖:this
public class LinkedList<E>extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable { transient int size = 0; //LinkedList中存放的元素個數 transient Node<E> first; //頭節點 transient Node<E> last; //尾節點 //構造方法,建立一個空的列表 public LinkedList() { } //將一個指定的集合添加到LinkedList中,先完成初始化,在調用添加操做 public LinkedList(Collection<? extends E> c) { this(); addAll(c); } //插入頭節點 private void linkFirst(E e) { final Node<E> f = first; //將頭節點賦值給f節點 //new 一個新的節點,此節點的data = e , pre = null , next - > f final Node<E> newNode = new Node<>(null, e, f); first = newNode; //將新建立的節點地址複製給first if (f == null) //f == null,表示此時LinkedList爲空 last = newNode; //將新建立的節點賦值給last else f.prev = newNode; //不然f.前驅指向newNode size++; modCount++; } //插入尾節點 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++; } //在succ節點前插入e節點,並修改各個節點之間的前驅後繼 void linkBefore(E e, Node<E> succ) { // assert succ != null; 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++; } //刪除頭節點 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; } //刪除尾節點 private E unlinkLast(Node<E> l) { // assert l == last && l != null; final E element = l.item; final Node<E> prev = l.prev; l.item = null; l.prev = null; // help GC last = prev; if (prev == null) first = null; else prev.next = null; size--; modCount++; return element; } //刪除指定節點 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; //若是前驅爲null, 說明此節點爲頭節點 } else { prev.next = next; //前驅結點的後繼節點指向當前節點的後繼節點 x.prev = null; //當前節點的前驅置空 } if (next == null) { //若是當前節點的後繼節點爲null ,說明此節點爲尾節點 last = prev; } else { next.prev = prev; //當前節點的後繼節點的前驅指向當前節點的前驅節點 x.next = null; //當前節點的後繼置空 } x.item = null; //當前節點的元素設置爲null ,等待垃圾回收 size--; modCount++; return element; } //獲取LinkedList中的第一個節點信息 public E getFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return f.item; } //獲取LinkedList中的最後一個節點信息 public E getLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return l.item; } //刪除頭節點 public E removeFirst() { final Node<E> f = first; if (f == null) throw new NoSuchElementException(); return unlinkFirst(f); } //刪除尾節點 public E removeLast() { final Node<E> l = last; if (l == null) throw new NoSuchElementException(); return unlinkLast(l); } //將添加的元素設置爲LinkedList的頭節點 public void addFirst(E e) { linkFirst(e); } //將添加的元素設置爲LinkedList的尾節點 public void addLast(E e) { linkLast(e); } //判斷LinkedList是否包含指定的元素 public boolean contains(Object o) { return indexOf(o) != -1; } //返回List中元素的數量 public int size() { return size; } //在LinkedList的尾部添加元素 public boolean add(E e) { linkLast(e); return true; } //刪除指定的元素 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; } //將集合中的元素添加到List中 public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } //將集合中的元素所有插入到List中,並從指定的位置開始 public boolean addAll(int index, Collection<? extends E> c) { checkPositionIndex(index); Object[] a = c.toArray(); //將集合轉化爲數組 int numNew = a.length; //獲取集合中元素的數量 if (numNew == 0) //集合中沒有元素,返回false return false; Node<E> pred, succ; if (index == size) { succ = null; pred = last; } else { succ = node(index); //獲取位置爲index的結點元素,並賦值給succ 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; } //刪除List中全部的元素 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++; } //獲取指定位置的元素 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; } //將節點放置在指定的位置 public void add(int index, E element) { checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); } //刪除指定位置的元素 public E remove(int index) { checkElementIndex(index); return unlink(node(index)); } //判斷索引是否合法 private boolean isElementIndex(int index) { return index >= 0 && index < size; } //判斷位置是否合法 private boolean isPositionIndex(int index) { return index >= 0 && index <= size; } //索引溢出信息 private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; } //檢查節點是否合法 private void checkElementIndex(int index) { if (!isElementIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } //檢查位置是否合法 private void checkPositionIndex(int index) { if (!isPositionIndex(index)) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); } //返回指定位置的節點信息 //LinkedList沒法隨機訪問,只能經過遍歷的方式找到相應的節點 //爲了提升效率,當前位置首先和元素數量的中間位置開始判斷,小於中間位置, //從頭節點開始遍歷,大於中間位置從尾節點開始遍歷 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; } } //返回第一次出現指定元素的位置 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; } //返回最後一次出現元素的位置 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; } //彈出第一個元素的值 public E peek() { final Node<E> f = first; return (f == null) ? null : f.item; } //獲取第一個元素 public E element() { return getFirst(); } //彈出第一元素,並刪除 public E poll() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); } //刪除第一個元素 public E remove() { return removeFirst(); } //添加到尾部 public boolean offer(E e) { return add(e); } //添加到頭部 public boolean offerFirst(E e) { addFirst(e); return true; } //插入到最後一個元素 public boolean offerLast(E e) { addLast(e); return true; } //隊列操做 //嘗試彈出第一個元素,可是不刪除元素 public E peekFirst() { final Node<E> f = first; return (f == null) ? null : f.item; } //隊列操做 //嘗試彈出最後一個元素,不刪除 public E peekLast() { final Node<E> l = last; return (l == null) ? null : l.item; } //彈出第一個元素,並刪除 public E pollFirst() { final Node<E> f = first; return (f == null) ? null : unlinkFirst(f); } //彈出最後一個元素,並刪除 public E pollLast() { final Node<E> l = last; return (l == null) ? null : unlinkLast(l); } //如隊列,添加到頭部 public void push(E e) { addFirst(e); } //出隊列刪除第一個節點 public E pop() { return removeFirst(); } //刪除指定元素第一次出現的位置 public boolean removeFirstOccurrence(Object o) { return remove(o); } //刪除指定元素最後一次出現的位置 public boolean removeLastOccurrence(Object o) { if (o == null) { for (Node<E> x = last; x != null; x = x.prev) { if (x.item == null) { unlink(x); return true; } } } else { for (Node<E> x = last; x != null; x = x.prev) { if (o.equals(x.item)) { unlink(x); return true; } } } return false; } //遍歷方法 public ListIterator<E> listIterator(int index) { checkPositionIndex(index); return new ListItr(index); } //內部類,實現ListIterator接口 private class ListItr implements ListIterator<E> { private Node<E> lastReturned = null; private Node<E> next; private int nextIndex; private int expectedModCount = modCount; ListItr(int index) { // assert isPositionIndex(index); next = (index == size) ? null : node(index); nextIndex = index; } 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() { return nextIndex > 0; } public E previous() { checkForComodification(); if (!hasPrevious()) throw new NoSuchElementException(); lastReturned = next = (next == null) ? last : next.prev; nextIndex--; return lastReturned.item; } public int nextIndex() { return nextIndex; } public int previousIndex() { return nextIndex - 1; } 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++; } public void set(E e) { if (lastReturned == null) throw new IllegalStateException(); checkForComodification(); lastReturned.item = e; } public void add(E e) { checkForComodification(); lastReturned = null; if (next == null) linkLast(e); else linkBefore(e, next); nextIndex++; expectedModCount++; } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } //靜態內部類,建立節點 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; } } /** * @since 1.6 */ public Iterator<E> descendingIterator() { return new DescendingIterator(); } /** * Adapter to provide descending iterators via ListItr.previous */ 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(); } } @SuppressWarnings("unchecked") private LinkedList<E> superClone() { try { return (LinkedList<E>) super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(); } } /** * Returns a shallow copy of this {@code LinkedList}. (The elements * themselves are not cloned.) * * @return a shallow copy of this {@code LinkedList} instance */ public Object 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; } 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; } @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) a = (T[])java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size); 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; } private static final long serialVersionUID = 876323262645176354L; //將對象寫入到輸出流中 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { // Write out any hidden serialization magic s.defaultWriteObject(); // Write out size s.writeInt(size); // Write out all elements in the proper order. for (Node<E> x = first; x != null; x = x.next) s.writeObject(x.item); } //從輸入流中將對象讀出 @SuppressWarnings("unchecked") private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden serialization magic s.defaultReadObject(); // Read in size int size = s.readInt(); // Read in all elements in the proper order. for (int i = 0; i < size; i++) linkLast((E)s.readObject()); } }
LinkedList() LinkedList(Collection<? extends E> c)
LinkedList沒有長度的概念,因此不存在容量不足的問題,所以不須要提供初始化大小的構造方法,所以值提供了兩個方法,一個是無參構造方法,初始一個LinkedList對象,和將指定的集合元素轉化爲LinkedList構造方法。spa
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++; }
添加方法默認是添加到LinkedList的尾部,首先將last指定的節點賦值給l節點,而後新建節點newNode ,此節點的前驅指向l節點,data = e , next = null , 並將新節點賦值給last節點,它成爲了最後一個節點,根據當前List是否爲空作出相應的操做。若不爲空將l的後繼指針修改成newNodw。 size +1 , modCount+1線程
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; }
刪除方法,先循環遍歷列表,找到item == o 的節點,在調用unlink()方法刪除