在閱讀LinkedList之前,建議還是將ArrayList 源碼進(jìn)行大概了解,其實(shí)向外部提供的方法以及設(shè)計(jì)思路是差不多的,只是LinkedList數(shù)據(jù)結(jié)構(gòu)不是array了,而是一個(gè)鏈表,那我們接下來(lái)就一起學(xué)習(xí)下LinkedList的源碼。
首先,我們從類(lèi)圖上來(lái)大體了解下 LinkedList 與 ArrayList的關(guān)系:
可以看出
LinkedList
不只是繼承、實(shí)現(xiàn)了 List
的那套東西,還實(shí)現(xiàn)了 Dueue
這個(gè)雙向隊(duì)列, 什么是雙向隊(duì)列呢,就是在隊(duì)列兩端都可以“插入”、“獲取” 數(shù)據(jù)。接下來(lái)我們還是以 ArrayList
的分析方式去分析LinkedList
。
基礎(chǔ)成員
transient int size = 0;
transient Link<E> voidLink;
private static final class Link<ET> {
ET data;
Link<ET> previous, next;
Link(ET o, Link<ET> p, Link<ET> n) {
data = o;
previous = p;
next = n;
}
}
這是 LinkedList
最基礎(chǔ)的組成部分, Link
這個(gè)靜態(tài)內(nèi)部類(lèi)是LinkedList
中每一個(gè)單元的類(lèi)型,數(shù)據(jù)是data
,previous
和next
分別指向鏈表的上游和下游;voidLink
可以理解是一個(gè)末尾節(jié)點(diǎn),size
是整個(gè)list的節(jié)點(diǎn)數(shù)量。從開(kāi)頭就可以看出,LinkedList
的數(shù)據(jù)結(jié)構(gòu)是一個(gè)雙向鏈表,這樣就避免了ArrayList
的自動(dòng)擴(kuò)容步驟,雖然在查找的時(shí)候占了些劣勢(shì)(需要按照鏈表的指向挨個(gè)去找,不如數(shù)組直接指向角標(biāo)快)。
構(gòu)造方法
/**
* Constructs a new empty instance of {@code LinkedList}.
*/
public LinkedList() {
voidLink = new Link<E>(null, null, null);
voidLink.previous = voidLink;
voidLink.next = voidLink;
}
/**
* Constructs a new instance of {@code LinkedList} that holds all of the
* elements contained in the specified {@code collection}. The order of the
* elements in this new {@code LinkedList} will be determined by the
* iteration order of {@code collection}.
*
* @param collection
* the collection of elements to add.
*/
public LinkedList(Collection<? extends E> collection) {
this();
addAll(collection);
}
LinkedList
提供了兩個(gè)構(gòu)造方法,第一個(gè)很簡(jiǎn)單,初始化voidLink
,并且將其上下游都指向自己;第二個(gè)構(gòu)造方法傳入一個(gè) collection
,如果不細(xì)究源碼細(xì)節(jié),根據(jù)ArrayList
的經(jīng)驗(yàn),想必肯定是傳入一個(gè)集合,將集合插入到這個(gè)空鏈表中。來(lái)舉個(gè)例子,向一個(gè)空的 LinkedList
插入 new1 和 new2節(jié)點(diǎn),我們用圖示來(lái)表達(dá)下這個(gè)過(guò)程:
上圖標(biāo)注比較明顯,對(duì)照代碼不難理解;下邊我們對(duì)源碼,從添加、移除、獲取等方面一一進(jìn)行了解,能用圖解盡量少說(shuō)話(huà):
添加
/**
* Adds the specified object at the end of this {@code LinkedList}.
*
* @param object
* the object to add.
* @return always true
*/
@Override
public boolean add(E object) {
return addLastImpl(object);
}
/**
* Adds the specified object at the end of this {@code LinkedList}.
*
* @param object
* the object to add.
*/
public void addLast(E object) {
addLastImpl(object);
}
private boolean addLastImpl(E object) {
Link<E> oldLast = voidLink.previous;
Link<E> newLink = new Link<E>(object, oldLast, voidLink);
voidLink.previous = newLink;
oldLast.next = newLink;
size++;
modCount++;
return true;
}
/**
* Adds the specified object at the beginning of this {@code LinkedList}.
*
* @param object
* the object to add.
*/
public void addFirst(E object) {
addFirstImpl(object);
}
private boolean addFirstImpl(E object) {
Link<E> oldFirst = voidLink.next;
Link<E> newLink = new Link<E>(object, voidLink, oldFirst);
voidLink.next = newLink;
oldFirst.previous = newLink;
size++;
modCount++;
return true;
}
/**
* Adds the objects in the specified Collection to this {@code LinkedList}.
*
* @param collection
* the collection of objects.
* @return {@code true} if this {@code LinkedList} is modified,
* {@code false} otherwise.
*/
@Override
public boolean addAll(Collection<? extends E> collection) {
int adding = collection.size();
if (adding == 0) {
return false;
}
Collection<? extends E> elements = (collection == this) ?
new ArrayList<E>(collection) : collection;
Link<E> previous = voidLink.previous;
for (E e : elements) {
Link<E> newLink = new Link<E>(e, previous, null);
previous.next = newLink;
previous = newLink;
}
previous.next = voidLink;
voidLink.previous = previous;
size += adding;
modCount++;
return true;
}
這個(gè)方法就是構(gòu)造方法里邊調(diào)用的addAll(collection)
,這里的流程圖在文章開(kāi)始的時(shí)候就已經(jīng)提到了,若有問(wèn)題的同學(xué)可以回構(gòu)造方法
那里再看看。
/**
* Inserts the specified object into this {@code LinkedList} at the
* specified location. The object is inserted before any previous element at
* the specified location. If the location is equal to the size of this
* {@code LinkedList}, the object is added at the end.
*
* @param location
* the index at which to insert.
* @param object
* the object to add.
* @throws IndexOutOfBoundsException
* if {@code location < 0 || location > size()}
*/
@Override
public void add(int location, E object) {
if (location >= 0 && location <= size) {
Link<E> link = voidLink;
if (location < (size / 2)) {
for (int i = 0; i <= location; i++) {
link = link.next;
}
} else {
for (int i = size; i > location; i--) {
link = link.previous;
}
}
Link<E> previous = link.previous;
Link<E> newLink = new Link<E>(object, previous, link);
previous.next = newLink;
link.previous = newLink;
size++;
modCount++;
} else {
throw new IndexOutOfBoundsException();
}
}
這個(gè)方法的有趣之處是參數(shù)中加了一個(gè)location
,最開(kāi)始查找location位置的link單元時(shí)采用了簡(jiǎn)單的一種二分查找方式,之后將 含有object
元素的newLink
插入到該位置,public boolean addAll(int location, Collection<? extends E> collection)
同理,只是批量操作。由于有了 ArrayList 的基礎(chǔ)和上邊的舉例講解,這里就 不對(duì) “獲取”、“移除”、“序列化”等做詳細(xì)講解了,原理都是一樣的,查找位置使用如上的二分查找,找到了就做一些響應(yīng)的鏈表操作。
public boolean offer(E o) {
return addLastImpl(o);
}
public E poll() {
return size == 0 ? null : removeFirst();
}
public E remove() {
return removeFirstImpl();
}
public E peek() {
return peekFirstImpl();
}
private E peekFirstImpl() {
Link<E> first = voidLink.next;
return first == voidLink ? null : first.data;
}
public E element() {
return getFirstImpl();
}
/**
* {@inheritDoc}
*
* @see java.util.Deque#offerFirst(java.lang.Object)
* @since 1.6
*/
public boolean offerFirst(E e) {
return addFirstImpl(e);
}
/**
* {@inheritDoc}
*
* @see java.util.Deque#offerLast(java.lang.Object)
* @since 1.6
*/
public boolean offerLast(E e) {
return addLastImpl(e);
}
/**
* {@inheritDoc}
*
* @see java.util.Deque#peekFirst()
* @since 1.6
*/
public E peekFirst() {
return peekFirstImpl();
}
/**
* {@inheritDoc}
*
* @see java.util.Deque#peekLast()
* @since 1.6
*/
public E peekLast() {
Link<E> last = voidLink.previous;
return (last == voidLink) ? null : last.data;
}
/**
* {@inheritDoc}
*
* @see java.util.Deque#pollFirst()
* @since 1.6
*/
public E pollFirst() {
return (size == 0) ? null : removeFirstImpl();
}
/**
* {@inheritDoc}
*
* @see java.util.Deque#pollLast()
* @since 1.6
*/
public E pollLast() {
return (size == 0) ? null : removeLastImpl();
}
/**
* {@inheritDoc}
*
* @see java.util.Deque#pop()
* @since 1.6
*/
public E pop() {
return removeFirstImpl();
}
/**
* {@inheritDoc}
*
* @see java.util.Deque#push(java.lang.Object)
* @since 1.6
*/
public void push(E e) {
addFirstImpl(e);
}
由于LinkedList
實(shí)現(xiàn)了 Deque
接口 (Deque
繼承Queue
),上邊這些方法就是具體針對(duì)Deque
接口的實(shí)現(xiàn)方式,反正我是感覺(jué)挺亂的,功能都一樣,但也要提供好多方法。。。。。。。
迭代器
這個(gè)我還是很想說(shuō)的,LinkedList
提供了兩個(gè)獲取iterator
的方法,分別是
@Override
public ListIterator<E> listIterator(int location) {
return new LinkIterator<E>(this, location);
}
public Iterator<E> descendingIterator() {
return new <E>(this);
}
從方法名上我們可以看出第一個(gè)是正序遍歷,第二個(gè)是倒敘遍歷,分別返回了ListIterator
和 ReverseLinkIterator
,這兩個(gè)靜態(tài)內(nèi)部類(lèi)的源碼如下:
private static final class LinkIterator<ET> implements ListIterator<ET> {
int pos, expectedModCount;
final LinkedList<ET> list;
Link<ET> link, lastLink;
LinkIterator(LinkedList<ET> object, int location) {
list = object;
expectedModCount = list.modCount;
if (location >= 0 && location <= list.size) {
// pos ends up as -1 if list is empty, it ranges from -1 to
// list.size - 1
// if link == voidLink then pos must == -1
link = list.voidLink;
if (location < list.size / 2) {
for (pos = -1; pos + 1 < location; pos++) {
link = link.next;
}
} else {
for (pos = list.size; pos >= location; pos--) {
link = link.previous;
}
}
} else {
throw new IndexOutOfBoundsException();
}
}
public void add(ET object) {
if (expectedModCount == list.modCount) {
Link<ET> next = link.next;
Link<ET> newLink = new Link<ET>(object, link, next);
link.next = newLink;
next.previous = newLink;
link = newLink;
lastLink = null;
pos++;
expectedModCount++;
list.size++;
list.modCount++;
} else {
throw new ConcurrentModificationException();
}
}
public boolean hasNext() {
return link.next != list.voidLink;
}
public boolean hasPrevious() {
return link != list.voidLink;
}
public ET next() {
if (expectedModCount == list.modCount) {
LinkedList.Link<ET> next = link.next;
if (next != list.voidLink) {
lastLink = link = next;
pos++;
return link.data;
}
throw new NoSuchElementException();
}
throw new ConcurrentModificationException();
}
public int nextIndex() {
return pos + 1;
}
public ET previous() {
if (expectedModCount == list.modCount) {
if (link != list.voidLink) {
lastLink = link;
link = link.previous;
pos--;
return lastLink.data;
}
throw new NoSuchElementException();
}
throw new ConcurrentModificationException();
}
public int previousIndex() {
return pos;
}
public void remove() {
if (expectedModCount == list.modCount) {
if (lastLink != null) {
Link<ET> next = lastLink.next;
Link<ET> previous = lastLink.previous;
next.previous = previous;
previous.next = next;
if (lastLink == link) {
pos--;
}
link = previous;
lastLink = null;
expectedModCount++;
list.size--;
list.modCount++;
} else {
throw new IllegalStateException();
}
} else {
throw new ConcurrentModificationException();
}
}
public void set(ET object) {
if (expectedModCount == list.modCount) {
if (lastLink != null) {
lastLink.data = object;
} else {
throw new IllegalStateException();
}
} else {
throw new ConcurrentModificationException();
}
}
}
/*
* NOTES:descendingIterator is not fail-fast, according to the documentation
* and test case.
*/
private class ReverseLinkIterator<ET> implements Iterator<ET> {
private int expectedModCount;
private final LinkedList<ET> list;
private Link<ET> link;
private boolean canRemove;
ReverseLinkIterator(LinkedList<ET> linkedList) {
list = linkedList;
expectedModCount = list.modCount;
link = list.voidLink;
canRemove = false;
}
public boolean hasNext() {
return link.previous != list.voidLink;
}
public ET next() {
if (expectedModCount == list.modCount) {
if (hasNext()) {
link = link.previous;
canRemove = true;
return link.data;
}
throw new NoSuchElementException();
}
throw new ConcurrentModificationException();
}
public void remove() {
if (expectedModCount == list.modCount) {
if (canRemove) {
Link<ET> next = link.previous;
Link<ET> previous = link.next;
next.next = previous;
previous.previous = next;
link = previous;
list.size--;
list.modCount++;
expectedModCount++;
canRemove = false;
return;
}
throw new IllegalStateException();
}
throw new ConcurrentModificationException();
}
}
先來(lái)看ListIterator
這個(gè)內(nèi)部類(lèi),expectedModCount == list.modCount
判斷和ArrayList
一樣,都是當(dāng)iterator
創(chuàng)建好之后,看LinkedList
是否經(jīng)過(guò)“添加”、“移除”等操作,expectedModCount
在iterator
初始化時(shí)賦值為modCount
,每次對(duì)iterator
的操作都會(huì)判斷二者是否相同,如果直接對(duì)LinkedList
進(jìn)行add
或者remove
操作,會(huì)導(dǎo)致modCount++
,此時(shí)如果再對(duì)iterator
操作時(shí),expectedModCount
沒(méi)變,就會(huì)拋出ConcurrentModificationException
異常;但ListIterator
比ArrayList
好的地方是不僅提供了remove
方法,還提供了add
方法,這樣,使用iterator
對(duì)LinkedList
操作起碼是單線(xiàn)程安全的。另外,需要注意的是,ReverseLinkIterator
沒(méi)有提供add
方法,所以一定注意,使用同一個(gè)iterator
實(shí)例時(shí),這個(gè)過(guò)程中不要對(duì)LinkedList
進(jìn)行add
操作。