給jdk寫註釋系列之jdk1.6容器(2):LinkedList源碼解析
本系列:
給jdk寫註釋系列之jdk1.6容器(1)-ArrayList源碼解析
LinkedList是基於鏈表結構的一種List,在分析LinkedList源碼前有必要對鏈表結構進行說明。
1.鏈表的概念
鏈表是由一系列非連續的節點組成的存儲結構,簡單分下類的話,鏈表又分為單向鏈表和雙向鏈表,而單向/雙向鏈表又可以分為循環鏈表和非循環鏈表,下面簡單就這四種鏈表進行圖解說明。
*** 1.1.單向鏈表*** 單向鏈表就是通過每個結點的指針指向下一個結點從而鏈接起來的結構,最後一個節點的next指向null。 *** 1. 2.單向循環鏈表*** 單向循環鏈表和單向列表的不同是,最後一個節點的next不是指向null,而是指向head節點,形成一個“環”。 ***1. 3.雙向鏈表*** 從名字就可以看出,雙向鏈表是包含兩個指針的,pre指向前一個節點,next指向後一個節點,但是第一個節點head的pre指向null,最後一個節點的tail指向null。
1. 4.雙向循環鏈表
雙向循環鏈表和雙向鏈表的不同在於,第一個節點的pre指向最後一個節點,最後一個節點的next指向第一個節點,也形成一個“環”。而LinkedList就是基於雙向循環鏈表設計的。
更形象的解釋下就是:雙向循環鏈表就像一群小孩手牽手圍成一個圈,第一個小孩的右手拉著第二個小孩的左手,第二個小孩的左手拉著第一個小孩的右手。。。最後一個小孩的右手拉著第一個小孩的左手。
ok,鏈表的概念介紹完了,下面進入寫註釋和源碼分析部分,但是在這之前還是要提醒一句,不是啰嗦哦,鏈表操作理解起來比數組困難了不少,所以務必要理解上面的圖解,如果源碼解析過程中遇到理解困難,請返回來照圖理解。
同樣先來看看LinkedList 的定義部分,
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
可以看出LinkedList 繼承AbstractSequentialList 抽象類,實現了List,Deque,Cloneable,Serializable 幾個接口,AbstractSequentialList 繼承 AbstractList,是對其中方法的再抽象,其主要作用是最大限度地減少了實現受“連續訪問”數據存儲(如鏈接列表)支持的此接口所需的工作,簡單說就是,如果需要快速的添加刪除數據等,用AbstractSequentialList抽象類,若是需要快速隨機的訪問數據等用AbstractList抽象類(詳細說明會在iterator 分析中進行解釋)。
Deque 是一個雙向隊列,也就是既可以先入先出,又可以先入後出,再直白一點就是既可以在頭部添加元素又在尾部添加元素,既可以在頭部獲取元素又可以在尾部獲取元素。看下Deque的定義:
public interface Deque<E> extends Queue<E> {
void addFirst(E e);
boolean offerFirst(E e);
boolean offerLast(E e);
E removeFirst();
E removeLast();
E pollFirst();
E pollLast();
E getFirst();
E getLast();
E peekFirst();
E peekLast();
boolean removeFirstOccurrence(Object o);
boolean removeLastOccurrence(Object o);
// Queue methods
boolean add(E e);
boolean offer(E e);
E remove();
E poll();
E element();
E peek();
// Stack methods
void push(E e);
E pop();
// Collection methods
boolean remove(Object o);
boolean contains(Object o);
public int size();
Iterator<E> iterator();
Iterator<E> descendingIterator();
}
3.底層存儲
明白了上面的鏈表概念,以及LinkedList是基於雙向循環鏈表設計的,下面在具體來看看LinkedList的底層存儲實現方式。
private transient Entry<E> header = new Entry<E>(null, null, null);
private transient int size = 0;
LinkedList中提供了上面兩個屬性,其中size和ArrayList中一樣用來計數,表示list的元素數量,而header則是鏈表的頭結點,Entry則是鏈表的節點對象。
private static class Entry<E> {
E element; // 當前存儲元素
Entry<E> next; // 下一個元素節點
Entry<E> previous; // 上一個元素節點
Entry(E element, Entry<E> next, Entry<E> previous) {
this.element = element;
this.next = next;
this.previous = previous;
}
}
Entry為LinkedList 的內部類,其中定義了當前存儲的元素,以及該元素的上一個元素和下一個元素。結合上面雙向鏈表的示意圖很容易看懂。
4.構造方法
/**
-
構造一個空的LinkedList .
*/
public LinkedList() {
//將header節點的前一節點和後一節點都設置為自身
header.next = header. previous = header ;
}/**
-
構造一個包含指定 collection 中的元素的列表,這些元素按其 collection 的叠代器返回的順序排列
*/
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
需要註意的是空的LinkedList構造方法,它將header節點的前一節點和後一節點都設置為自身,這裏便說明LinkedList 是一個雙向循環鏈表,如果只是單存的雙向鏈表而不是循環鏈表,他的實現應該是這樣的:
public LinkedList() {
header.next = null;
header. previous = null;
}
非循環鏈表的情況應該是header節點的前一節點和後一節點均為null(參見鏈表圖解)。
5.增加增加方法的代碼讀起來比較不容易理解,需要的時候請結合鏈表圖解。
/**
-
將一個元素添加至list尾部
*/
public boolean add(E e) {
// 在header前添加元素e,header前就是最後一個結點啦,就是在最後一個結點的後面添加元素e
addBefore(e, header);
return true;
}
/**- 在指定位置添加元素
*/
public void add(int index, E element) {
// 如果index等於list元素個數,則在隊尾添加元素(header之前),否則在index節點前添加元素
addBefore(element, (index== size ? header : entry(index)));
}
private Entry<E> addBefore(E e, Entry<E> entry) {
// 用entry創建一個要添加的新節點,next為entry,previous為entry.previous,意思就是新節點插入entry前面,確定自身的前後引用,
Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
// 下面修改newEntry的前後節點的引用,確保其鏈表的引用關系是正確的
// 將上一個節點的next指向自己
newEntry. previous.next = newEntry;
// 將下一個節點的previous指向自己
newEntry. next.previous = newEntry;
// 計數+1
size++;
modCount++;
return newEntry;
}
到這裏可以發現一點疑慮,header作為雙向循環鏈表的頭結點是不保存數據的,也就是說hedaer中的element永遠等於null。 - 在指定位置添加元素
/**
-
添加一個集合元素到list中
*/
public boolean addAll(Collection<? extends E> c) {
// 將集合元素添加到list最後的尾部
return addAll(size , c);
}/**
- 在指定位置添加一個集合元素到list中
*/
public boolean addAll(int index, Collection<? extends E> 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++;
// 找出要插入元素的前後節點
// 獲取要插入index位置的下一個節點,如果index正好是lsit尾部的位置那麽下一個節點就是header,否則需要查找index位置的節點
Entry<E> successor = (index== size ? header : entry(index));
// 獲取要插入index位置的上一個節點,因為是插入,所以上一個點擊就是未插入前下一個節點的上一個
Entry<E> predecessor = successor. previous;
// 循環插入
for (int i=0; i<numNew; i++) {
// 構造一個節點,確認自身的前後引用
Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
// 將插入位置上一個節點的下一個元素引用指向當前元素(這裏不修改下一個節點的上一個元素引用,是因為下一個節點隨著循環一直在變)
predecessor. next = e;
// 最後修改插入位置的上一個節點為自身,這裏主要是為了下次遍歷後續元素插入在當前節點的後面,確保這些元素本身的順序
predecessor = e;
}
// 遍歷完所有元素,最後修改下一個節點的上一個元素引用為遍歷的最後一個元素
successor. previous = predecessor;// 修改計數器
size += numNew;
return true;
}增加方法的代碼理解起來可能有些困難,但是只要理解了雙向鏈表的存儲結構,掌握增加的核心邏輯就可以了,這裏總結一下往鏈表中增加元素的核心邏輯:1.將元素轉換為鏈表節點,2.增加該節點的前後引用(即pre和next分別指向哪一個節點),3.前後節點對該節點的引用(前節點的next指向該節點,後節點的pre指向該節點)。現在再看下就這麽簡單麽,就是改變前後的互相指向關系(看圖增加元素前後的變化)。
其實刪除也是一樣的對不對?下面看看刪除方法的實現。
PS:不要問我entry()方法是怎麽回事,這裏先不講,打我也不講。。。
6.刪除 - 在指定位置添加一個集合元素到list中
/**
- 刪除第一個匹配的指定元素
*/
public boolean remove(Object o) {
// 遍歷鏈表找到要被刪除的節點
if (o==null) {
for (Entry<E> e = header .next; e != header; e = e.next ) {
if (e.element ==null) {
remove(e);
return true;
}
}
} else {
for (Entry<E> e = header .next; e != header; e = e.next ) {
if (o.equals(e.element )) {
remove(e);
return true;
}
}
}
return false;
}
private E remove(Entry<E> e) {
if (e == header )
throw new NoSuchElementException();
// 被刪除的元素,供返回
E result = e. element;
// 下面修正前後對該節點的引用
// 將該節點的上一個節點的next指向該節點的下一個節點
e. previous.next = e.next;
// 將該節點的下一個節點的previous指向該節點的上一個節點
e. next.previous = e.previous;
// 修正該節點自身的前後引用
e. next = e.previous = null;
// 將自身置空,讓gc可以盡快回收
e. element = null;
// 計數器減一
size--;
modCount++;
return result;
}
上面對於鏈表增加元素總結了,一句話就是“改變前後的互相指向關系”,刪除也是同樣的道理,由於節點被刪除,該節點的上一個節點和下一個節點互相拉一下小手就可以了,註意的是“互相”,不能一廂情願。
7.修改
/**
- 修改指定位置索引位置的元素
*/
public E set( int index, E element) {
// 查找index位置的節點
Entry<E> e = entry(index);
// 取出該節點的元素,供返回使用
E oldVal = e. element;
// 用新元素替換舊元素
e. element = element;
// 返回舊元素
return oldVal;
}
set方法看起來簡單了很多,只要修改該節點上的元素就好了,但是不要忽略了這裏的entry()方法,重點就是它。
8.查詢
終於到查詢了,終於發現了上面經常出現的那個方法entry()根據index查詢節點,我們知道數組是有下標的,通過下標操作天然的支持根據index查詢元素,而鏈表中是沒有index概念呢,那麽怎麽樣才能通過index查詢到對應的元素呢,下面就來看看LinkedList是怎麽實現的。
/**
-
查找指定索引位置的元素
*/
public E get( int index) {
return entry(index).element ;
}/**
- 返回指定索引位置的節點
*/
private Entry<E> entry( int index) {
// 越界檢查
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException( "Index: "+index+
", Size: "+size );
// 取出頭結點
Entry<E> e = header;
// size>>1右移一位代表除以2,這裏使用簡單的二分方法,判斷index與list的中間位置的距離
if (index < (size >> 1)) {
// 如果index距離list中間位置較近,則從頭部向後遍歷(next)
for (int i = 0; i <= index; i++)
e = e. next;
} else {
// 如果index距離list中間位置較遠,則從頭部向前遍歷(previous)
for (int i = size; i > index; i--)
e = e. previous;
}
return e;
}
現在知道了,LinkedList是通過從header開始index計為0,然後一直往下遍歷(next),直到到底index位置。為了優化查詢效率,LinkedList采用了二分查找(這裏說的二分只是簡單的一次二分),判斷index與size中間位置的距離,采取從header向後還是向前查找。
到這裏我們明白,基於雙向循環鏈表實現的LinkedList,通過索引Index的操作時低效的,index所對應的元素越靠近中間所費時間越長。而向鏈表兩端插入和刪除元素則是非常高效的(如果不是兩端的話,都需要對鏈表進行遍歷查找)。
9.是否包含
/**
- Returns <tt>true</tt> if this list contains the specified element.
- More formally, returns <tt>true</tt> if and only if this list contains
- at least one element <tt>e</tt> such that
- <tt>(o==null ? e==null : o.equals(e))</tt>.
- @param o element whose presence in this list is to be tested
-
@return <tt> true</tt> if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}/**
- Returns the index of the first occurrence of the specified element
- in this list, or -1 if this list does not contain the element.
- More formally, returns the lowest index <tt>i</tt> such that
- <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
- or -1 if there is no such index.
- @param o element to search for
- @return the index of the first occurrence of the specified element in
- this list, or -1 if this list does not contain the element
*/
public int indexOf(Object o) {
int index = 0;
if (o==null) {
for (Entry e = header .next; e != header; e = e.next ) {
if (e.element ==null)
return index;
index++;
}
} else {
for (Entry e = header .next; e != header; e = e.next ) {
if (o.equals(e.element ))
return index;
index++;
}
}
return -1;
}
/**
- Returns the index of the last occurrence of the specified element
- in this list, or -1 if this list does not contain the element.
- More formally, returns the highest index <tt>i</tt> such that
- <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
- or -1 if there is no such index.
- @param o element to search for
- @return the index of the last occurrence of the specified element in
- this list, or -1 if this list does not contain the element
*/
public int lastIndexOf(Object o) {
int index = size ;
if (o==null) {
for (Entry e = header .previous; e != header; e = e.previous ) {
index--;
if (e.element ==null)
return index;
}
} else {
for (Entry e = header .previous; e != header; e = e.previous ) {
index--;
if (o.equals(e.element ))
return index;
}
}
return -1;
}
和public boolean remove(Object o) 一樣,indexOf查詢元素位於容器的索引位置,都是需要對鏈表進行遍歷操作,當然也就是低效了啦。
10.判斷容量
/**
- Returns the number of elements in this list.
-
@return the number of elements in this list
*/
public int size() {
return size ;
}/**
- {@inheritDoc}
- <p>This implementation returns <tt>size() == 0 </tt>.
*/
public boolean isEmpty() {
return size() == 0;
}
和ArrayList一樣,基於計數器size操作,容量判斷很方便。
到這裏LinkedList就分析完了,不對好像還差些什麽對不對?是什麽呢,就是最開始說的Deque雙端隊列,明白了鏈表原理和LinkedList的基本crud操作,Deque的LinkedList實現就已經是so easy了,我們簡單看下。
11.LinkedList實現的Deque雙端隊列
/**
- Adds the specified element as the tail (last element) of this list.
- @param e the element to add
- @return <tt> true</tt> (as specified by {@link Queue#offer})
- @since 1.5
*/
public boolean offer(E e) {
return add(e);
}
/**
- Retrieves and removes the head (first element) of this list
- @return the head of this list, or <tt>null </tt> if this list is empty
- @since 1.5
*/
public E poll() {
if (size ==0)
return null;
return removeFirst();
}
/**
- Removes and returns the first element from this list.
- @return the first element from this list
- @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
return remove(header .next);
}
/**
- Retrieves, but does not remove, the head (first element) of this list.
- @return the head of this list, or <tt>null </tt> if this list is empty
- @since 1.5
*/
public E peek() {
if (size ==0)
return null;
return getFirst();
}
/**
- Returns the first element in this list.
- @return the first element in this list
-
@throws NoSuchElementException if this list is empty
*/
public E getFirst() {
if (size ==0)
throw new NoSuchElementException();return header .next. element;
}
/**
- Pushes an element onto the stack represented by this list. In other
- words, inserts the element at the front of this list.
- <p>This method is equivalent to {@link #addFirst}.
- @param e the element to push
- @since 1.6
*/
public void push(E e) {
addFirst(e);
}
/**
- Inserts the specified element at the beginning of this list.
- @param e the element to add
*/
public void addFirst(E e) {
addBefore(e, header.next );
}總結:
看看Deque 的實現是不是很簡單,邏輯都是基於上面講的鏈表操作的,對於隊列的一些概念我不打算在這裏講,是因為後面隊列會單獨拿出來分析啦,這裏只要理解基於鏈表實現的list內部是怎麽操作的就可以啦。。。
LinkedList 完!
給jdk寫註釋系列之jdk1.6容器(2):LinkedList源碼解析