LinkedList源码解析1.8
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
//不可序列化,元素个数
transient int size = 0;
//不可序列化,首元素
transient Node<E> first;
//不可序列化,尾元素
transient Node<E> last;
/**
* Constructs an empty list.
*/
public LinkedList() {
}
//添加一组内容到链表中
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
//将元素e插入到链表的头部,
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
//判断原来是否为空,如果为空,那么设置first,last 都为同一节点
//否则连接到新的first节点之后.
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}
//将e插入到链表尾部,逻辑同上
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;
else
l.next = newNode;
size++;
modCount++;
}
//插入到一个元素之后
void linkBefore(E e, Node<E> succ) {
// assert succ != null;
final Node<E> pred = succ.prev;
final Node<E> newNode = new Node<>(pred, e, succ);
succ.prev = newNode;
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
//移除头一个元素
private E unlinkFirst(Node<E> f) {
// assert f == first && f != null;
//上句不判断是因为外层调用已经判断了
final E element = f.item;
final Node<E> next = f.next;
f.item = null;
f.next = null; // help GC
first = next;
//判断位置处理最后一个元素和下一个元素
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
//移除最后一个,逻辑大致同上
private E unlinkLast(Node<E> l) {
// assert l == last && l != null;
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;
else
prev.next = null;
size--;
modCount++;
return element;
}
//移除任意一个节点,也可以移除第一个或者最后一个
E unlink(Node<E> x) {
// assert x != null;
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;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
//获取第一个节点
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;
}
//移除第一个元素
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);
}
//添加到头
public void addFirst(E e) {
linkFirst(e);
}
//添加到尾
public void addLast(E e) {
linkLast(e);
}
//是否包含元素,包含则返回true,euqals判断
public boolean contains(Object o) {
return indexOf(o) != -1;
}
//返回元素的个数
public int size() {
return size;
}
//添加一个元素到末尾
public boolean add(E e) {
linkLast(e);
return true;
}
//移除一个元素,判断方法o == null? get(x)==null:o.equals(get(x)),删除第一个匹配到的
public boolean remove(Object o) {
if (o == null) {
for (Node<E> x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
//添加集合c到链表的末尾,有并发问题,特别是当c是自己的时候
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
//插入到指定位置
public boolean addAll(int index, Collection<? extends E> c) {
//检查位置是否合法
checkPositionIndex(index);
Object[] a = c.toArray();
int numNew = a.length;
if (numNew == 0)
return false;
//判断当前的位置到底在最后还是中
Node<E> pred, succ;
if (index == size) {
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);
//当链表没有元素的时候,first和last都是null
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
//添加完元素之后,如果是往末尾添加,需要处理last的引用
//如果是中间插入,需要连接后面的节点
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
//清除所有节点的链接,虽然清除所有链是不必要的,但是这样帮助gc
public void clear() {
// Clearing all of the links between nodes is "unnecessary", but:
// - helps a generational GC if the discarded nodes inhabit
// more than one generation
// - is sure to free memory even if there is a reachable Iterator
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++;
}
// Positional Access Operations
// 下面都是位置访问的操作
//获取指定索引的元素,首先判断位置。
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;
}
//插入一个元素,根据是否在队尾插入,处理逻辑不同
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
//移除一个节点,使用unlink,不用考虑是否是第一个或者最后一个
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
//校验是否元素的合法位置,元素的位置0-(size-1)
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
//校验是否合法的位置,0-size
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
/**
* Constructs an IndexOutOfBoundsException detail message.
* Of the many possible refactorings of the error handling code,
* this "outlining" performs best with both server and client VMs.
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
//返回一个非空的节点,由于调用处都判断了index范围,所以内部没有判断
Node<E> node(int index) {
// assert isElementIndex(index);
//通过判断index和size/2的比较,决定从前往后还是从后往前遍历
if (index < (size >> 1)) {
Node<E> x = 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;
}
}
// Search Operations
//搜索元素的操作,从前往后找
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;
}
//从后往前找
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;
}
// Queue operations.
//返回头一个元素但是不删除,first == null,返回null
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
//返回第一个元素。first == null,则抛出异常
public E element() {
return getFirst();
}
//返回第一个元素,当first == null,返回null。否则删除第一个元素,并返回删除的元素。如果链表元素为null则返回值就不知道是队列没有还是返回元素是null
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
//返回第一个元素并删除,如果不存在则抛出异常
public E remove() {
return removeFirst();
}
//在末尾添加元素 和add(e)一样
public boolean offer(E e) {
return add(e);
}
// Deque operations 双端队列操作
//添加到头
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
//添加到尾部
public boolean offerLast(E e) {
addLast(e);
return true;
}
//获取第一个,但是不删除。f==null返回null
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
//返回最后一个但是不删除,l == null,返回null
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
//弹出并且删除第一个,f == null,返回null
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
//同上,返回最后一个
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 boolean removeFirstOccurrence(Object o) {
return remove(o);
}
//同上,从尾开始
public boolean removeLastOccurrence(Object o) {
if (o == null) {
for (Node<E> x = last; x != null; x = x.prev) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node<E> x = last; x != null; x = x.prev) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
//返回一个迭代器,fail-fast。
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;
ListItr(int index) {
// assert isPositionIndex(index);
next = (index == size) ? null : node(index);
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;
}
//检查是否并发操作,返回前一个
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;
}
//必须先有返回,才能remove,移除最近返回的那个元素
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;
}
//添加一个元素,添加到当前遍历到的位置.如果后面还有,插入到它之前.如果是最后一个,就处理一下last引用
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();
}
}
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;
}
}
/**
* @since 1.6
*/
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();
}
}
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
//复制了元素,生成一个新的链表
public Object clone() {
LinkedList<E> clone = superClone();
//初始化clone 链表
// Put clone into "virgin" state
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
// Initialize clone with our elements
for (Node<E> x = first; x != null; x = x.next)
clone.add(x.item);
return clone;
}
//新开辟一个数组去存放对象,调用端可以自动的修改数组不影响原链表
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;
}
//类型是运行时知道的,如果数组的长度大于size,那么重新生成一个数组,用来放元素.
//如果数组的长度大于size,那么会将a[size]设置为null,后面的元素不动
@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;
}
private static final long serialVersionUID = 876323262645176354L;
/**
* Saves the state of this {@code LinkedList} instance to a stream
* (that is, serializes it).
*
* @serialData The size of the list (the number of elements it
* contains) is emitted (int), followed by all of its
* elements (each an Object) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out size
s.writeInt(size);
// Write out all elements in the proper order.
for (Node<E> x = first; x != null; x = x.next)
s.writeObject(x.item);
}
/**
* Reconstitutes this {@code LinkedList} instance from a stream
* (that is, deserializes it).
*/
@SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in size
int size = s.readInt();
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
linkLast((E)s.readObject());
}
//返回可分割的迭代器.
@Override
public Spliterator<E> spliterator() {
return new LLSpliterator<E>(this, -1, 0);
}
/** A customized variant of Spliterators.IteratorSpliterator */
//可以分段的迭代器
static final class LLSpliterator<E> implements Spliterator<E> {
//1往左移动10位,用0填补.即1024
static final int BATCH_UNIT = 1 << 10; // batch array size increment
//1往左移动25位,用0填补.即33554432
static final int MAX_BATCH = 1 << 25; // max batch array size;
final LinkedList<E> list; // null OK unless traversed
Node<E> current; // current node; null until initialized
//估计大小,构造的时候为-1
int est; // size estimate; -1 until first needed
int expectedModCount; // initialized when est set
int batch; // batch size for splits
LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
this.list = list;
this.est = est;
this.expectedModCount = expectedModCount;
}
//调用的时候如果未初始化就初始化参数
final int getEst() {
int s; // force initialization
final LinkedList<E> lst;
if ((s = est) < 0) {
if ((lst = list) == null)
s = est = 0;
else {
expectedModCount = lst.modCount;
current = lst.first;
s = est = lst.size;
}
}
return s;
}
//返回大小
public long estimateSize() { return (long) getEst(); }
//尝试切分,如果链表小于1024,那么不会分段.
//最大分段大小是MAX_BATCH
public Spliterator<E> trySplit() {
Node<E> p;
int s = getEst();
if (s > 1 && (p = current) != null) {
int n = batch + BATCH_UNIT;
if (n > s)
n = s;
if (n > MAX_BATCH)
n = MAX_BATCH;
Object[] a = new Object[n];
int j = 0;
do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
current = p;
batch = j;
est = s - j;
return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
}
return null;
}
public void forEachRemaining(Consumer<? super E> action) {
Node<E> p; int n;
if (action == null) throw new NullPointerException();
if ((n = getEst()) > 0 && (p = current) != null) {
current = null;
est = 0;
do {
E e = p.item;
p = p.next;
action.accept(e);
} while (p != null && --n > 0);
}
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
}
public boolean tryAdvance(Consumer<? super E> action) {
Node<E> p;
if (action == null) throw new NullPointerException();
if (getEst() > 0 && (p = current) != null) {
--est;
E e = p.item;
current = p.next;
action.accept(e);
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
public int characteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
}
以下都是个人理解,如果有问请多多包涵,欢迎留言指导。
问题
- 为什么linkBefore,linkLast不是private?
- final修饰的局部变量有什么好处?linkFirst、linkLast、linkBefore中.
疑问:为了性能??
- 为什么有了unlink(Node x),还要unlinkLast和unlinkFirst
疑问:unlink(Node x)可以移除各种情况,并且对比unlinkLast或者unlinkFirst,区别在于每次都判断first和last,还有每次需要获取item,next,pre,有必要写成3个方法么?为什么不都用unlink?
linkBefore不能替代linkFirst么?
疑问:如果要替代的话, linkBefore(E e, Node<E> succ)需要对参数succ做非空判断。
哪些为null的时候抛异常。
答:关键是element(),remove(),其他pop(),getFirst(),getLast(),removeFirst(),removeLast()
注意
- Poll方法的返回值可能无法分别(1)到底元素是null还是(2)没有元素在链表中。
- toArray(T[] a)如果a.length >size,那么只会把a[size]设置为null,其他不动.