在阅读LinkedList之前,建议还是将ArrayList 源码进行大概了解,其实向外部提供的方法以及设计思路是差不多的,只是LinkedList数据结构不是array了,而是一个链表,那我们接下来就一起学习下LinkedList的源码。
首先,我们从类图上来大体了解下 LinkedList 与 ArrayList的关系:
可以看出 LinkedList 不只是继承、实现了 List 的那套东西,还实现了 Dueue 这个双向队列, 什么是双向队列呢,就是在队列两端都可以“插入”、“获取” 数据。接下来我们还是以 ArrayList的分析方式去分析LinkedList。
基础成员
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 最基础的组成部分, Link 这个静态内部类是LinkedList中每一个单元的类型,数据是data,previous和next 分别指向链表的上游和下游;voidLink 可以理解是一个末尾节点,size是整个list的节点数量。从开头就可以看出,LinkedList 的数据结构是一个双向链表,这样就避免了ArrayList的自动扩容步骤,虽然在查找的时候占了些劣势(需要按照链表的指向挨个去找,不如数组直接指向角标快)。
构造方法
/**
* 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提供了两个构造方法,第一个很简单,初始化voidLink,并且将其上下游都指向自己;第二个构造方法传入一个 collection,如果不细究源码细节,根据ArrayList的经验,想必肯定是传入一个集合,将集合插入到这个空链表中。来举个例子,向一个空的 LinkedList 插入 new1 和 new2节点,我们用图示来表达下这个过程:
上图标注比较明显,对照代码不难理解;下边我们对源码,从添加、移除、获取等方面一一进行了解,能用图解尽量少说话:
添加
/**
* 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;
}这个方法就是构造方法里边调用的addAll(collection),这里的流程图在文章开始的时候就已经提到了,若有问题的同学可以回构造方法那里再看看。
/**
* 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();
}
}这个方法的有趣之处是参数中加了一个location,最开始查找location位置的link单元时采用了简单的一种二分查找方式,之后将 含有object 元素的newLink插入到该位置,public boolean addAll(int location, Collection<? extends E> collection)同理,只是批量操作。由于有了 ArrayList 的基础和上边的举例讲解,这里就 不对 “获取”、“移除”、“序列化”等做详细讲解了,原理都是一样的,查找位置使用如上的二分查找,找到了就做一些响应的链表操作。
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实现了 Deque 接口 (Deque继承Queue),上边这些方法就是具体针对Deque接口的实现方式,反正我是感觉挺乱的,功能都一样,但也要提供好多方法。。。。。。。
迭代器
这个我还是很想说的,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,这两个静态内部类的源码如下:
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这个内部类,expectedModCount == list.modCount 判断和ArrayList一样,都是当iterator创建好之后,看LinkedList是否经过“添加”、“移除”等操作,expectedModCount在iterator初始化时赋值为modCount,每次对iterator的操作都会判断二者是否相同,如果直接对LinkedList进行add或者remove操作,会导致modCount++,此时如果再对iterator操作时,expectedModCount没变,就会抛出ConcurrentModificationException 异常;但ListIterator比ArrayList好的地方是不仅提供了remove方法,还提供了add方法,这样,使用iterator对LinkedList操作起码是单线程安全的。另外,需要注意的是,ReverseLinkIterator 没有提供add方法,所以一定注意,使用同一个iterator实例时,这个过程中不要对LinkedList进行add操作。
共同学习,写下你的评论
评论加载中...
作者其他优质文章



