Java集合之LinkedList源碼解析

原文地址前端

LinkedList

  • 在Java.util包下
  • 繼承自AbstractSequentialList
  • 實現 List 接口,能對它進行隊列操做。
  • 實現 Deque 接口,即能將LinkedList看成雙端隊列使用。
  • 實現了Cloneable接口,即覆蓋了函數clone(),能克隆。
  • 實現java.io.Serializable接口,這意味着LinkedList支持序列化,能經過序列化去傳輸。
  • 容許包含null值
  • 迭代器能夠快速報錯
  • 非線程安全的,若是在多線程中使用(修改),須要在外部做同步處理。

LinkedList是一種能夠在任何位置進行高效地插入和移除操做的有序序列,它是基於雙向鏈表實現的。內部有三個變量,size表示鏈表中元素的個數, first指向鏈表頭部,last指向鏈表尾部。 結構圖以下圖所示java

LinkedList.png

下面是LinkedList中Node節點的定義,Node類是LinkedList的靜態內部類。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;
	}
}
複製代碼

構造方法(Construction method)

LinkedList提供了兩種種方式的構造器,構造一個空列表、以及構造一個包含指定collection的元素的列表, 這些元素按照該collection的迭代器返回的順序排列的。編程

public LinkedList() {
}

public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);   // 調用addAll方法,構建一個包含指定集合c的列表
}
複製代碼

添加元素

由於LinkedList即實現了List接口,又實現了Deque接口,因此LinkedList既能夠添加將元素添加到尾部,也能夠將元素添加到指定索引位置,還能夠添加添加整個集合;另外既能夠在頭部添加,又能夠在尾部添加。後端

//添加元素做爲第一個元素
public void addFirst(E e) {
    linkFirst(e);
}
//店家元素做爲最後一個元素
public void addLast(E e) {
    linkLast(e);
}

//使用對應參數做爲第一個節點,內部使用
private void linkFirst(E e) {
	final Node<E> f = first;//獲得首節點
	final Node<E> newNode = new Node<>(null, e, f);//建立一個節點
	first = newNode;        //更新首節點
	if (f == null)
		last = newNode;     //若是以前首節點爲空(size==0),那麼尾節點就是首節點
	else
		f.prev = newNode;   //若是以前首節點不爲空,以前的首節點的前一個節點爲當前首節點
	size++;                 //長度+1
	modCount++;             //修改次數+1
}
//使用對應參數做爲尾節點
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;    //若是以前尾節點爲空(size==0),首節點即尾節點
	else
		l.next = newNode;   //若是以前尾節點不爲空,以前的尾節點的後一個就是當前的尾節點
	size++;
	modCount++;
}

//在非空節點succ以前插入元素E。
void linkBefore(E e, Node<E> succ) {
	final Node<E> pred = succ.prev;//獲取前一個節點
	final Node<E> newNode = new Node<>(pred, e, succ);//使用參數建立新的節點
	succ.prev = newNode;//當前節點指向新的節點
	if (pred == null)
		first = newNode;//若是前一個節點爲null,新的節點就是首節點
	else
		pred.next = newNode;//若是存在前節點,那麼前節點的向後指向新節點
	size++;
	modCount++;
}

//添加指定集合的元素到列表,默認從最後開始添加
public boolean addAll(Collection<? extends E> c) {
	return addAll(size, c);//size表示最後一個位置
}

/* 從指定位置(而不是下標!下標即索引從0開始,位置能夠看作從1開始,其實也是0)後面添加指定集合的元素到列表中,只要有至少一次添加就會返回true index換成position應該會更好理解,因此也就是從索引爲index(position)的元素的前面索引爲index-1的後面添加! 固然位置能夠爲0啊,爲0的時候就是從位置0(雖然它不存在)後面開始添加嘛,因此理所固然就是添加到第一個位置(位置1的前面)的前面 好比列表:0 1 2 3,若是此處index=4(實際索引爲3),就是在元素3後面添加;若是index=3(實際索引爲2),就在元素2後面添加。 */
public boolean addAll(int index, Collection<? extends E> c) {
	checkPositionIndex(index);  //檢查索引是否正確(0<=index<=size)
	Object[] a = c.toArray();   //獲得元素數組
	int numNew = a.length;      //獲得元素個數
	if (numNew == 0)            //若沒有元素要添加,直接返回false
		return false;
	Node<E> pred, succ;
	if (index == size) {    //若是是在末尾開始添加,當前節點後一個節點初始化爲null,前一個節點爲尾節點
		succ = null;        //這裏能夠看作node(index),不過index=size了(index最大隻能是size-1),因此這裏的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;    //若當前節點爲null,則新加的節點爲首節點
		else
			pred.next = newNode;//若是存在前節點,前節點會向後指向新加的節點
		pred = newNode;         //新加的節點成爲前一個節點
	}
	if (succ == null) {
		//pred.next = null //加上這句也能夠更好的理解
		last = pred;        //若是是從最後開始添加的,則最後添加的節點成爲尾節點
	} else {
		pred.next = succ;   //若是不是從最後開始添加的,則最後添加的節點向後指向以前獲得的後續第一個節點
		succ.prev = pred;   //當前,後續的第一個節點也應改成向前指向最後一個添加的節點
	}
	size += numNew;
	modCount++;
	return true;
}

//將指定的元素(E element)插入到列表的指定位置(index)
public void add(int index, E element) {
	checkPositionIndex(index); //index >= 0 && index <= size

	if (index == size) 
		linkLast(element); //尾插入
	else
		linkBefore(element, node(index));  //中間插入
}
複製代碼

linkBefore的添加步驟:數組

  1. 建立newNode節點,將newNode的後繼指針指向succ,前驅指針指向pred
  2. 將succ的前驅指針指向newNode
  3. 根據pred是否爲null,進行不一樣操做。
  • 若是pred爲null,說明該節點插入在頭節點以前,要重置first頭節點
  • 若是pred不爲null,那麼直接將pred的後繼指針指向newNode便可

addAll的添加步驟:安全

  1. 檢查index索引範圍
  2. 獲得集合數據
  3. 獲得插入位置的前驅和後繼節點
  4. 遍歷數據,將數據插入到指定位置

刪除元素

一樣的LinkedList也提供了不少方法來刪除元素多線程

// 刪除首節點並返回刪除前首節點的值,內部使用 (f == first && f != null)
private E unlinkFirst(Node<E> f) {
	final E element = f.item;      // 獲取首節點的值 
	final Node<E> next = f.next;   // 獲取首節點的後一個節點
	f.item = null;
	f.next = null; // help GC
	first = next;                 // 更新首節點
	if (next == null)             //若是不存在下一個節點,則首尾都爲null
		last = null;
	else
		next.prev = null;        //若是存在下一個節點,那它的前指針爲null
	size--;
	modCount++;
	return element;
}

// 刪除尾節點,並返回尾節點的元素 (assert l == last && l != null)
private E unlinkLast(Node<E> l) {
	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;   //若是前一個節點不存在,則首尾都爲null
	else
		prev.next = null;//若是前一個節點存在,前後指向null
	size--;
	modCount++;
	return element;
}

// 刪除指定節點x並返回節點的值(x != null)
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;  //help GC
	}
	if (next == null) {
		last = prev;    //若是後一個節點爲空(如當前節點爲尾節點),當前節點前一個成爲新的尾節點
	} else {
		next.prev = prev;//若是後一個節點不爲空,後一個節點向前指向當前的前一個節點
		x.next = null;  //help GC
	}
	x.item = null;   //help GC
	size--;
	modCount++;
	return element;
}

//刪除第一個元素並返回刪除的元素
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);
}
複製代碼

序列化方法

private static final long serialVersionUID = 876323262645176354L;

//序列化:將linkedList的「大小,全部的元素值」都寫入到輸出流中
private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException {
	s.defaultWriteObject();
	s.writeInt(size);

	for (Node<E> x = first; x != null; x = x.next)
		s.writeObject(x.item);
}

//反序列化:先將LinkedList的「大小」讀出,而後將「全部的元素值」讀出
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException {
	s.defaultReadObject();
	int size = s.readInt();

	for (int i = 0; i < size; i++)
		linkLast((E)s.readObject());  //以尾插入的方式
}
複製代碼

隊列操做

//提供普通隊列和雙向隊列的功能,固然,也能夠實現棧,FIFO,FILO
//出隊(從前端),得到第一個元素,不存在會返回null,不會刪除元素(節點)
public E peek() {
	final Node<E> f = first;
	return (f == null) ? null : f.item;
}
//出隊(從前端),不刪除元素,若爲null會拋出異常而不是返回null
public E element() {
	return getFirst();
}
//出隊(從前端),若是不存在會返回null,存在的話會返回值並移除這個元素(節點)
public E poll() {
	final Node<E> f = first;
	return (f == null) ? null : unlinkFirst(f);
}
//出隊(從前端),若是不存在會拋出異常而不是返回null,存在的話會返回值並移除這個元素(節點)
public E remove() {
	return removeFirst();
}
//入隊(從後端),始終返回true
public boolean offer(E e) {
	return add(e);
}
//入隊(從前端),始終返回true
public boolean offerFirst(E e) {
	addFirst(e);
	return true;
}
//入隊(從後端),始終返回true
public boolean offerLast(E e) {
	addLast(e);//linkLast(e)
	return true;
}
//出隊(從前端),得到第一個元素,不存在會返回null,不會刪除元素(節點)
public E peekFirst() {
	final Node<E> f = first;
	return (f == null) ? null : f.item;
 }
//出隊(從後端),得到最後一個元素,不存在會返回null,不會刪除元素(節點)
public E peekLast() {
	final Node<E> l = last;
	return (l == null) ? null : l.item;
}
//出隊(從前端),得到第一個元素,不存在會返回null,會刪除元素(節點)
public E pollFirst() {
	final Node<E> f = first;
	return (f == null) ? null : unlinkFirst(f);
}
//出隊(從後端),得到最後一個元素,不存在會返回null,會刪除元素(節點)
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 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();
	}
}

public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        return new ListItr(index);
}

private class ListItr implements ListIterator<E> {
	private Node<E> lastReturned;
	private Node<E> next;
	private int nextIndex;
	private int expectedModCount = modCount;//保存當前modCount,確保fail-fast機制

	ListItr(int index) {
		next = (index == size) ? null : node(index);//獲得當前索引指向的next節點
		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;
	}

	//獲取前一個節點,將next節點向前移
	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++;
	}

	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();
	}

	final void checkForComodification() {
		if (modCount != expectedModCount)
			throw new ConcurrentModificationException();
	}
}
複製代碼

在ListIterator的構造器中,獲得了當前位置的節點,就是變量next。next()方法返回當前節點的值並將next指向其後繼節點,previous()方法返回當前節點的前一個節點的值並將next節點指向其前驅節點。併發

因爲Node是一個雙向節點,因此這用了一個節點就能夠實現從前向後迭代和從後向前迭代。另外在ListIterator初始時,exceptedModCount保存了當前的modCount,若是在迭代期間,有操做改變了鏈表的底層結構,那麼再操做迭代器的方法時將會拋出ConcurrentModificationException。函數

fail-fast

fail-fast 機制是java集合(Collection)中的一種錯誤機制。當多個線程對同一個集合的內容進行操做時,就可能會產生fail-fast事件。例如:當某一個線程A經過iterator去遍歷某集合的過程當中,若該集合的內容被其餘線程所改變了;那麼線程A訪問集合時,就會拋出ConcurrentModificationException異常,產生fail-fast事件。

快速失敗(fail—fast)

在用迭代器遍歷一個集合對象時,若是遍歷過程當中對集合對象的內容進行了修改(增長、刪除、修改),則會拋出Concurrent Modification Exception。

**原理:**迭代器在遍歷時直接訪問集合中的內容,而且在遍歷過程當中使用一個 modCount 變量。集合在被遍歷期間若是內容發生變化,就會改變modCount的值。每當迭代器使用hashNext()/next()遍歷下一個元素以前,都會檢測modCount變量是否爲expectedmodCount值,是的話就返回遍歷;不然拋出異常,終止遍歷。

注意:這裏異常的拋出條件是檢測到 modCount!=expectedmodCount 這個條件。若是集合發生變化時修改modCount值恰好又設置爲了expectedmodCount值,則異常不會拋出。所以,不能依賴於這個異常是否拋出而進行併發操做的編程,這個異常只建議用於檢測併發修改的bug。

場景:java.util包下的集合類都是快速失敗的,不能在多線程下發生併發修改(迭代過程當中被修改)。

安全失敗(fail—safe)

採用安全失敗機制的集合容器,在遍歷時不是直接在集合內容上訪問的,而是先複製原有集合內容,在拷貝的集合上進行遍歷。

**原理:**因爲迭代時是對原集合的拷貝進行遍歷,因此在遍歷過程當中對原集合所做的修改並不能被迭代器檢測到,因此不會觸發Concurrent Modification Exception。

缺點:基於拷貝內容的優勢是避免了Concurrent Modification Exception,但一樣地,迭代器並不能訪問到修改後的內容,即:迭代器遍歷的是開始遍歷那一刻拿到的集合拷貝,在遍歷期間原集合發生的修改迭代器是不知道的。

場景:java.util.concurrent包下的容器都是安全失敗,能夠在多線程下併發使用,併發修改。

其餘方法

//獲取第一個元素
public E getFirst() {
	final Node<E> f = first;//獲得首節點
	if (f == null)          //若是爲空,拋出異常
		throw new NoSuchElementException();
	return f.item;
}
//獲取最後一個元素
public E getLast() {
	final Node<E> l = last;//獲得尾節點
	if (l == null)          //若是爲空,拋出異常
		throw new NoSuchElementException();
	return l.item;
}

//檢查是否包含某個元素,返回bool
public boolean contains(Object o) {
	return indexOf(o) != -1;//返回指定元素的索引位置,不存在就返回-1,而後比較返回bool值
}
//返回列表長度
public int size() {
	return size;
}

//清空表
public void clear() {     // help GC
	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;
}

//獲取指定位置的節點
Node<E> node(int index) {
	if (index < (size >> 1)) {//若是位置索引小於列表長度的一半(或一半減一),從前面開始遍歷;
		Node<E> x = first;//index==0時不會循環,直接返回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;
	}
}

//獲取指定元素從first開始的索引位置,不存在就返回-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;
}
//獲取指定元素從first開始最後出現的索引,不存在就返回-1
//但實際查找是從last開始的
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;
}

//返回此 LinkedList實例的淺拷貝
public Object clone() {
	LinkedList<E> clone = superClone();

	clone.first = clone.last = null;
	clone.size = 0;
	clone.modCount = 0;

	for (Node<E> x = first; x != null; x = x.next)
		clone.add(x.item);

	return clone;
}

//返回一個包含LinkedList中全部元素值的數組
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;
}

//若是給定的參數數組長度足夠,則將ArrayList中全部元素按序存放於參數數組中,並返回
//若是給定的參數數組長度小於LinkedList的長度,則返回一個新分配的、長度等於LinkedList長度的、包含LinkedList中全部元素的新數組
@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;
}
複製代碼
相關文章
相關標籤/搜索