在閱讀LinkedList之前抑钟,建議還是將ArrayList 源碼進行大概了解,其實向外部提供的方法以及設(shè)計思路是差不多的,只是LinkedList數(shù)據(jù)結(jié)構(gòu)不是array了,而是一個鏈表喧半,那我們接下來就一起學(xué)習(xí)下LinkedList的源碼箕速。
首先零截,我們從類圖上來大體了解下 LinkedList 與 ArrayList的關(guān)系:
可以看出
LinkedList
不只是繼承锭汛、實現(xiàn)了 List
的那套東西荣月,還實現(xiàn)了 Dueue
這個雙向隊列管呵, 什么是雙向隊列呢,就是在隊列兩端都可以“插入”哺窄、“獲取” 數(shù)據(jù)捐下。接下來我們還是以 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
這個靜態(tài)內(nèi)部類是LinkedList
中每一個單元的類型坷襟,數(shù)據(jù)是data
,previous
和next
分別指向鏈表的上游和下游生年;voidLink
可以理解是一個末尾節(jié)點婴程,size
是整個list的節(jié)點數(shù)量。從開頭就可以看出抱婉,LinkedList
的數(shù)據(jù)結(jié)構(gòu)是一個雙向鏈表档叔,這樣就避免了ArrayList
的自動擴容步驟,雖然在查找的時候占了些劣勢(需要按照鏈表的指向挨個去找蒸绩,不如數(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òu)造方法,第一個很簡單患亿,初始化voidLink
传蹈,并且將其上下游都指向自己;第二個構(gòu)造方法傳入一個 collection
步藕,如果不細究源碼細節(jié)惦界,根據(jù)ArrayList
的經(jīng)驗,想必肯定是傳入一個集合漱抓,將集合插入到這個空鏈表中表锻。來舉個例子恕齐,向一個空的 LinkedList
插入 new1 和 new2節(jié)點乞娄,我們用圖示來表達下這個過程:
上圖標(biāo)注比較明顯,對照代碼不難理解显歧;下邊我們對源碼仪或,從添加、移除士骤、獲取等方面一一進行了解范删,能用圖解盡量少說話:
添加
/**
* 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òu)造方法里邊調(diào)用的addAll(collection)
,這里的流程圖在文章開始的時候就已經(jīng)提到了拷肌,若有問題的同學(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();
}
}
這個方法的有趣之處是參數(shù)中加了一個location
旨巷,最開始查找location位置的link單元時采用了簡單的一種二分查找方式,之后將 含有object
元素的newLink
插入到該位置添忘,public boolean addAll(int location, Collection<? extends E> collection)
同理采呐,只是批量操作。由于有了 ArrayList 的基礎(chǔ)和上邊的舉例講解搁骑,這里就 不對 “獲取”斧吐、“移除”、“序列化”等做詳細講解了仲器,原理都是一樣的煤率,查找位置使用如上的二分查找,找到了就做一些響應(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
實現(xiàn)了 Deque
接口 (Deque
繼承Queue
)蝶糯,上邊這些方法就是具體針對Deque
接口的實現(xiàn)方式,反正我是感覺挺亂的辆沦,功能都一樣裳涛,但也要提供好多方法。众辨。端三。。鹃彻。郊闯。。
迭代器
這個我還是很想說的蛛株,LinkedList
提供了兩個獲取iterator
的方法团赁,分別是
@Override
public ListIterator<E> listIterator(int location) {
return new LinkIterator<E>(this, location);
}
public Iterator<E> descendingIterator() {
return new <E>(this);
}
從方法名上我們可以看出第一個是正序遍歷,第二個是倒敘遍歷谨履,分別返回了ListIterator
和 ReverseLinkIterator
欢摄,這兩個靜態(tài)內(nè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();
}
}
先來看ListIterator
這個內(nèi)部類,expectedModCount == list.modCount
判斷和ArrayList
一樣笋粟,都是當(dāng)iterator
創(chuàng)建好之后怀挠,看LinkedList
是否經(jīng)過“添加”、“移除”等操作害捕,expectedModCount
在iterator
初始化時賦值為modCount
绿淋,每次對iterator
的操作都會判斷二者是否相同,如果直接對LinkedList
進行add
或者remove
操作尝盼,會導(dǎo)致modCount++
吞滞,此時如果再對iterator
操作時,expectedModCount
沒變盾沫,就會拋出ConcurrentModificationException
異常裁赠;但ListIterator
比ArrayList
好的地方是不僅提供了remove
方法殿漠,還提供了add
方法,這樣佩捞,使用iterator
對LinkedList
操作起碼是單線程安全的凸舵。另外,需要注意的是失尖,ReverseLinkIterator
沒有提供add
方法啊奄,所以一定注意,使用同一個iterator
實例時掀潮,這個過程中不要對LinkedList
進行add
操作菇夸。