LinkedList簡介
??LinkedList是基于雙向循環鏈表(從源碼中可以很容易看出)實現的,除了可以當做鏈表來操作外,它還可以當做棧、隊列和雙端隊列來使用。
??LinkedList在內部定義了一個叫做Entry類型的內部類(1.7之后換成了Node內部類),這個Entry就是一個節點,鏈表中的節點,這個節點有3個屬性,分別是元素item(當前節點要表示的值), 前節點prev(當前節點之前位置上的一個節點),后節點next(當前節點后面位置的一個節點)。
??LinkedList提供高效的插入,刪除元素的功能。但是不具備ArrayList那種高效的隨機訪問。
LinkedList源碼剖析
基于JDK 1.6和最新的JDK的數據結構稍微有點出入,但是思路是一樣的,80%代碼都已經給出。
public class MyLinkedList<T> extends AbstractSequentialList<T> implements List<T>, Deque<T>, Cloneable, Serializable {
private static final long serialVersionUID = -3358195569371661044L;
// 集合鏈表內節點數量
transient int size = 0;
// 鏈表的表頭,表頭不包含任何數據。Entry是個鏈表類數據結構。
private transient Entry<T> header = new Entry<T>(null, null, null);
// 默認構造函數:創建一個空的鏈表
public MyLinkedList() {
header.next = header.previous = header;
}
// 包含“集合”的構造函數:創建一個包含“集合”的LinkedList
public MyLinkedList(Collection<? extends T> c) {
addAll(c);
}
// 將“集合(c)”添加到LinkedList中。
// 實際上,是從雙向鏈表的末尾開始,將“集合(c)”添加到雙向鏈表中。
public boolean addAll(Collection<? extends T> c) {
return addAll(size, c);
}
// 從雙向鏈表的index開始,將“集合(c)”添加到雙向鏈表中。
public boolean addAll(int index, Collection<? extends T> c) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index +
", Size: " + size);
Object[] a = c.toArray();
// 獲取集合的長度
int numNew = a.length;
if (numNew == 0)
return false;
modCount++;
// 設置“當前要插入節點的后一個節點”
Entry<T> successor = (index == size ? header : entry(index));
// 設置“當前要插入節點的前一個節點”
Entry<T> predecessor = successor.previous;
// 將集合(c)全部插入雙向鏈表中
for (int i = 0; i < numNew; i++) {
Entry<T> e = new Entry<T>((T) a[i], successor, predecessor);
predecessor.next = e;
predecessor = e;
}
successor.previous = predecessor;
// 調整LinkedList的實際大小
size += numNew;
return true;
}
// 雙向鏈表的節點所對應的數據結構。
// 包含3部分:上一節點,下一節點,當前節點值。
private static class Entry<T> {
// 當前節點所包含的值
T element;
// 下一個節點
Entry<T> next;
// 上一個節點
Entry<T> previous;
public Entry(T element, Entry<T> next, Entry<T> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
// 將節點數據是e的添加到entry節點之前。
private Entry<T> addBefore(T e, Entry<T> entry) {
// 新建節點newEntry,將newEntry插入到節點e之前;并且設置newEntry的數據是e
Entry<T> newEntry = new Entry<>(e, entry, entry.previous);
newEntry.next.previous = newEntry;
newEntry.previous.next = newEntry;
size++;
modCount++;
return newEntry;
}
// 將節點從鏈表中刪除(LinkedList所有remove方法最終都調用這個)
private T remove(Entry<T> e) {
if (e == header)
throw new NoSuchElementException();
T result = e.element;
e.next.previous = e.previous;
e.previous.next = e.next;
e.previous = e.next = null;
e.element = null;
size--;
modCount++;
return result;
}
// 將元素e添加到LinkedList中
public boolean add(T e) {
// 將節點(節點數據是e)添加到表頭(header)之前。即,將節點添加到雙向鏈表的末端
addBefore(e, header);
return true;
}
// 在index前添加節點,且節點的值為element
public void add(int index, T element) {
addBefore(element, (index == size ? header : entry(index)));
}
// 從LinkedList中刪除元素(o)
// 從鏈表開始查找,如存在元素(o)則刪除該元素并返回true;否則,返回false
@Override
public boolean remove(Object o) {
if (o == null) {
// 若o為null的刪除情況
for (Entry<T> e = header.next; e != header; e = e.next) {
if (e.element == null) {
remove(e);
return true;
}
}
} else {
// 若o不為null的刪除情況
for (Entry<T> e = header.next; e != header; e = e.next) {
if (o.equals(e.element)) {
remove(e);
return true;
}
}
}
return false;
}
// remove一個位置index的節點
@Override
public T remove(int index) {
return remove(entry(index));
}
// 獲取雙向鏈表中指定位置的節點, 很重要的方法!!!
private Entry<T> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
Entry<T> h = header;
// 獲取index處的節點。
// 若index < 雙向鏈表長度的1/2,則從前先后查找;
// 否則,從后向前查找。
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
h = h.next;
} else {
for (int i = size; i > index; i--)
h = h.previous;
}
return h;
}
@Override
public boolean offerFirst(T t) {
addFirst(t);
return true;
}
@Override
public boolean offerLast(T t) {
addLast(t);
return true;
}
@Override
public T removeFirst() {
return remove(header.next);
}
@Override
public T removeLast() {
return remove(header.previous);
}
@Override
public T pollFirst() {
if (size == 0)
return null;
return removeFirst();
}
@Override
public T pollLast() {
if (size == 0)
return null;
return removeLast();
}
@Override
public T getFirst() {
if (size==0)
throw new NoSuchElementException();
// 鏈表的表頭header中不包含數據。
// 這里返回header所指下一個節點所包含的數據。
return header.next.element;
}
@Override
public T getLast() {
if (size==0)
throw new NoSuchElementException();
// 由于LinkedList是雙向鏈表;而表頭header不包含數據。
// 因而,這里返回表頭header的前一個節點所包含的數據。
return header.previous.element;
}
@Override
public T peekFirst() {
if (size == 0)
return null;
return getFirst();
}
@Override
public T peekLast() {
if (size == 0)
return null;
return getLast();
}
@Override
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
// 從LinkedList末尾向前查找,刪除第一個值為元素(o)的節點
// 從鏈表開始查找,如存在節點的值為元素(o)的節點,則刪除該節點
@Override
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Entry<T> e = header.previous; e != header; e = e.previous) {
if (e.element == null) {
remove(e);
return true;
}
}
} else {
for (Entry<T> e = header.previous; e != header; e = e.previous) {
if (o.equals(e.element)) {
remove(e);
return true;
}
}
}
return false;
}
@Override
public boolean offer(T t) {
return add(t);
}
@Override
public T remove() {
return removeFirst();
}
@Override
public T poll() {
if (size == 0)
return null;
return removeFirst();
}
@Override
public T element() {
return getFirst();
}
// 返回第一個節點
@Override
public T peek() {
if (size == 0)
return null;
return getFirst();
}
@Override
public void push(T t) {
addFirst(t);
}
@Override
public T pop() {
return removeFirst();
}
@Override
public int size() {
return size;
}
@Override
public boolean contains(Object o) {
return indexOf(o) != -1;
}
// 從前向后查找,返回“值為對象(o)的節點對應的索引”
// 不存在就返回-1
@Override
public int indexOf(Object o) {
int index = 0;
if (o == null) {
for (Entry<T> e = header.next; e != header; e = e.next) {
if (e.element == null)
return index++;
}
} else {
for (Entry<T> e = header.next; e != header; e = e.next) {
if (o.equals(e.element))
return index++;
}
}
return -1;
}
// List迭代器
// 返回“index到末尾的全部節點”對應的ListIterator對象, list.iterator(); 方法調用的就是這個方法最后, (index=0)
@Override
public ListIterator<T> listIterator(int index) {
return new ListItr(index);
}
// ListItr內部類
private class ListItr implements ListIterator<T> {
// 下一個節點
private Entry<T> next;
// 上一次返回的節點
private Entry<T> lastReturned = header;
// 下一個節點對應的索引值
private int nextIndex;
// 期望的改變計數。用來實現fail-fast機制。
private int expectedModCount = modCount;
public ListItr(int index) {
// index的有效性處理
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
// 若 “index 小于 ‘雙向鏈表長度的一半’”,則從第一個元素開始往后查找;
// 否則,從最后一個元素往前查找。
if (index < (size >> 1)) {
// 初始化下一個節點
next = header.next;
for (nextIndex = 0; nextIndex < index; nextIndex++)
next = next.next;
} else {
next = header;
for (nextIndex = size; nextIndex > index; nextIndex--)
next = next.previous;
}
}
// 是否存在下一個元素
@Override
public boolean hasNext() {
// 通過元素索引是否等于“雙向鏈表大小”來判斷是否達到最后。
return nextIndex != size;
}
// 獲取下一個元素
@Override
public T next() {
checkForComodification();
int i = nextIndex;
if (i >= size)
throw new NoSuchElementException();
nextIndex++;
lastReturned = next;
// next指向鏈表的下一個元素
next = next.next;
return lastReturned.element;
}
@Override
public boolean hasPrevious() {
// 通過元素索引是否等于0,來判斷是否達到開頭。
return nextIndex != 0;
}
@Override
public T previous() {
if (nextIndex == 0)
throw new NoSuchElementException();
// next指向鏈表的上一個元素
lastReturned = next = next.previous;
nextIndex--;
checkForComodification();
return lastReturned.element;
}
// 獲取下一個元素的索引
@Override
public int nextIndex() {
return nextIndex;
}
@Override
public int previousIndex() {
return nextIndex - 1;
}
// 刪除雙向鏈表中的當前節點
@Override
public void remove() {
checkForComodification();
Entry<T> lastNext = lastReturned.next;
try {
MyLinkedList.this.remove(lastReturned);
} catch (NoSuchElementException e) {
throw new IllegalStateException();
}
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
// 重置lastReturned
lastReturned = header;
expectedModCount++;
}
@Override
public void set(T e) {
if (lastReturned == header)
throw new IllegalStateException();
checkForComodification();
lastReturned.element = e;
}
@Override
public void add(T e) {
checkForComodification();
// 重置lastReturned
lastReturned = header;
addBefore(e, next);
nextIndex++;
expectedModCount++;
}
// 判斷 “modCount和expectedModCount是否相等”,依次來實現fail-fast機制。
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
// 返回LinkedList的Object[]數組
public Object[] toArray() {
// 新建Object[]數組
Object[] result = new Object[size];
int i = 0;
// 將鏈表中所有節點的數據都添加到Object[]數組中
for (Entry<T> e = header.next; e != header; e = e.next)
result[i++] = e.element;
return result;
}
// 返回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 (Entry<T> e = (Entry<T>) header.next; e != header; e = e.next)
result[i++] = e.element;
if (a.length > size)
a[size] = null;
return a;
}
// 克隆函數。返回LinkedList的克隆對象。
public Object clone() {
MyLinkedList<T> clone = null;
// 克隆一個LinkedList克隆對象
try {
clone = (MyLinkedList<T>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError();
}
// 新建LinkedList表頭節點
clone.header = new Entry<T>(null, null, null);
clone.header.next = clone.header.previous = clone.header;
clone.size = 0;
clone.modCount = 0;
// 將鏈表中所有節點的數據都添加到克隆對象中
for (Entry<T> e = header.next; e != header; e = e.next)
clone.add(e.element);
return clone;
}
}
源碼幾個重點方法講解
private Entry<T> addBefore(T e, Entry<T> entry);
?這個方法就是將節點數據是e的添加到某個entry節點之前,如下圖所示,在1節點之前加入0節點
??1. 先新建節點newEntry。
??2. 新建節點newEntry的next和previous引用分別指向1節點和3節點。
??3. 3節點的next和1節點的previous指向新建節點newEntry。
?
private T remove(Entry<T> e)
// 將節點從鏈表中刪除(LinkedList所有remove方法最終都調用這個)
?這個方法就是將節點數據e的刪除,如下圖所示,刪除1節點:
??1. 先把3節點next引用從指向1節點變成指向7節點。
??2. 再把7節點previous引用從指向1節點變成指向3節點。
??3. 清空1節點的previous和next節點,都指向null。
??3. 清空1節點的previous和next節點element數據,使得element = null;
?? 等待GC。
LinkedList和ArrayList的比較
??LinkedList和ArrayList的設計理念完全不一樣,ArrayList基于數組,而LinkedList基于節點,也就是鏈表。所以LinkedList內部沒有容量這個概念,因為是鏈表,鏈表是無界的
??兩者的使用場景不同,ArrayList適用于讀多寫少的場合。LinkedList適用于寫多讀少的場合。 剛好相反。 那是因為LinkedList要找節點的話必須要遍歷一個一個節點,直到找到為止。而ArrayList完全不需要,因為ArrayList內部維護著一個數組,直接根據索引拿到需要的元素即可。