//LinkedList源码 jdk版本1.8.0_121
public class LinkedList extends AbstractSequentialList implements List, Deque, Cloneable, java.io.Serializable
{transient int size = 0;/*** 指向第一节点
* first和last要么都为null,要么都不为null。不要把节点node和节点的item混淆*/
transient Nodefirst;/*** 指向最后一个节点*/
transient Nodelast;/*** 构造一个空的LinkedList*/
publicLinkedList() {
}/*** 通过集合来构建LinkedList*/
public LinkedList(Collection extends E>c) {this();
addAll(c);
}/*** 将元素放在第一个位置
* 具体做法就是创建一个新的节点newNode,newNode的item设置为该元素,然后newNode的next指向原来的第一个节点
* 将first指向新的节点,如果是第一次添加节点就将last也指向该节点,如果不是第一次添加就将原来的第一个节点的prev指向新的节点*/
private voidlinkFirst(E e) {final Node f =first;final Node newNode = new Node<>(null, e, f);
first=newNode;if (f == null)//第一次添加节点
last =newNode;else//不是第一次添加节点
f.prev =newNode;
size++;
modCount++;
}/*** 将元素放在最后一个位置
* 创建一个新的节点newNode,将newNode的prev指向原来的最后一个节点
* 将last指向newNode,如果是第一次添加就将first也指向newNode,如果不是第一次添加就将原来最后一个节点的next指向newNode*/
voidlinkLast(E e) {final Node l =last;final Node newNode = new Node<>(l, e, null);
last=newNode;if (l == null)
first=newNode;elsel.next=newNode;
size++;
modCount++;
}/*** 将元素插入到另外一个节点的前面
* 根据元素创建一个新的节点newNode,newNode的prev指向另一个节点succ的prev所指向的节点,newNode的next指向succ
* 如果succ的prev为null,也就是说我succ为第一个节点,那么要将fisrt指向newNode,如果succ不是第一个节点,那么就让succ的prev所指向的节点的next指向newNode*/
void linkBefore(E e, Nodesucc) {//assert succ != null;
final Node pred =succ.prev;final Node newNode = new Node<>(pred, e, succ);
succ.prev=newNode;if (pred == null)
first=newNode;elsepred.next=newNode;
size++;
modCount++;
}/*** 将节点从第一个位置上移除
* 将第一个元素的item和next都置为null,方便垃圾回收
* first指向将next指向的节点,如果next指向的节点为null,就将last也设置为null(也就是说这个要移除的节点是链表中的最后一个节点)
* 如果next指向的节点不为null,那么就将next指向的节点的prev设置为null*/
private E unlinkFirst(Nodef) {//assert f == first && f != null;
final E element =f.item;final Node next =f.next;
f.item= null;
f.next= null; //help GC
first =next;if (next == null)
last= null;elsenext.prev= null;
size--;
modCount++;returnelement;
}/*** 移除最后一个元素
* 将最后一个元素的item和prev置为null,它的last本来就为null所以不用管
* 然后将last指向prev指向的节点,如果prev指向的节点为null,那么就将first也设置为null(也就是说这个要移除的节点是链表中的最后一个节点)
* 如果prev指向的节点不为null,那么就将prev指向节点的next设置为null*/
private E unlinkLast(Nodel) {//assert l == last && l != null;
final E element =l.item;final Node prev =l.prev;
l.item= null;
l.prev= null; //help GC
last =prev;if (prev == null)
first= null;elseprev.next= null;
size--;
modCount++;returnelement;
}/*** 移除一个节点
* 如果该节点是第一个节点,就将first指向该节点的下一个节点,否则将该节点的上一个节点的next指向该节点的下一个节点
* 如果该节点是最后一个节点,就将last指向该节点的上一个节点,否则就将下一个节点的prev指向该节点的上一个节点
* 将当前的接电点的prev、item、next都置为null,方便GC*/E unlink(Nodex) {//assert x != null;
final E element =x.item;final Node next =x.next;final Node 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++;returnelement;
}/*** 获取list中的第一个元素,直接通过first节点,获取其中的item,如果是空list会报错*/
publicE getFirst() {final Node f =first;if (f == null)throw newNoSuchElementException();returnf.item;
}/*** 获取list中的最后一个元素,直接通过last来获取,如果是空list会报错*/
publicE getLast() {final Node l =last;if (l == null)throw newNoSuchElementException();returnl.item;
}/*** 删除第一个节点,如果是空list会报错*/
publicE removeFirst() {final Node f =first;if (f == null)throw newNoSuchElementException();returnunlinkFirst(f);
}/*** 删除最后一个节点,如果是空list会报错*/
publicE removeLast() {final Node l =last;if (l == null)throw newNoSuchElementException();returnunlinkLast(l);
}/*** 将元素加入到list最前面*/
public voidaddFirst(E e) {
linkFirst(e);
}/*** 将元素加入到list最后面*/
public voidaddLast(E e) {
linkLast(e);
}/*** 判断list是否包含该对象*/
public booleancontains(Object o) {return indexOf(o) != -1;
}/*** 返回元素的个数*/
public intsize() {returnsize;
}/*** 将元素添加到LinkedList尾部*/
public booleanadd(E e) {
linkLast(e);return true;
}/*** 删除某个对象
* 迭代从前往后进行匹配,如果满足条件就删除,最多删除一次,后续再匹配上也不删除*/
public booleanremove(Object o) {if (o == null) {for (Node x = first; x != null; x =x.next) {if (x.item == null) {
unlink(x);return true;
}
}
}else{for (Node x = first; x != null; x =x.next) {if(o.equals(x.item)) {
unlink(x);return true;
}
}
}return false;
}/*** 批量加入集合中的元素到list尾部*/
public boolean addAll(Collection extends E>c) {returnaddAll(size, c);
}/*** 批量加入集合中的元素到list的index处*/
public boolean addAll(int index, Collection extends E>c) {
checkPositionIndex(index);//如果传入的集合中元素个数为0,直接返回false
Object[] a =c.toArray();int numNew =a.length;if (numNew == 0)return false;
Node pred, succ;//pred 是指向插入的第一个元素的前一个节点,succ是指向插入的 最后一个元素的后一个节点
if (index == size) {//如果index为size那就说明是插在最后一个元素的后面
succ = null;
pred=last;
}else{
succ=node(index);
pred=succ.prev;
}//循环将集合中的元素加入到list中
for(Object o : a) {
@SuppressWarnings("unchecked") E e =(E) o;
Node newNode = new Node<>(pred, e, null);if (pred == null)
first=newNode;elsepred.next=newNode;
pred=newNode;
}//如果succ为null,则将last指向最后添加的元素,如果不为null则和加入的最后一个元素关联起来
if (succ == null) {
last=pred;
}else{
pred.next=succ;
succ.prev=pred;
}
size+=numNew;
modCount++;return true;
}/*** 清空LinkedList中所有的数据
* 这里循环清空了所有节点之间的联系,虽然这不是必须的,但是这样做会有助于分代GC*/
public voidclear() {//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 x = first; x != null; ) {
Node next =x.next;
x.item= null;
x.next= null;
x.prev= null;
x=next;
}
first= last = null;
size= 0;
modCount++;
}//Positional Access Operations 位置相关的一些操作,也就是和下标index有关
/*** 获取某个下标处的元素*/
public E get(intindex) {
checkElementIndex(index);returnnode(index).item;
}/*** 设置某个下标处的元素*/
public E set(intindex, E element) {
checkElementIndex(index);
Node x =node(index);
E oldVal=x.item;
x.item=element;returnoldVal;
}/*** 在某个下标处添加一个元素*/
public void add(intindex, E element) {
checkPositionIndex(index);if (index == size)//添加在最后面
linkLast(element);elselinkBefore(element, node(index));
}/*** 删除某个下标处的元素*/
public E remove(intindex) {
checkElementIndex(index);returnunlink(node(index));
}/*** 判断下标处有没有元素*/
private boolean isElementIndex(intindex) {return index >= 0 && index
}/*** 判断这个index是否可以用于添加或者迭代,和上面的相比只是多了一个size值。*/
private boolean isPositionIndex(intindex) {return index >= 0 && index <=size;
}/*** 越界异常语句*/
private String outOfBoundsMsg(intindex) {return "Index: "+index+", Size: "+size;
}private void checkElementIndex(intindex) {if (!isElementIndex(index))throw newIndexOutOfBoundsException(outOfBoundsMsg(index));
}private void checkPositionIndex(intindex) {if (!isPositionIndex(index))throw newIndexOutOfBoundsException(outOfBoundsMsg(index));
}/*** 返回index处非null的节点,index 小于 size的一半就从前面开始查找,否则从后面开始查找*/Node node(intindex) {//assert isElementIndex(index);
if (index < (size >> 1)) {
Node x =first;for (int i = 0; i < index; i++)
x=x.next;returnx;
}else{
Node x =last;for (int i = size - 1; i > index; i--)
x=x.prev;returnx;
}
}//Search Operations
/*** 查找该对象在list中的下标,第一次出现的下标,没有返回-1*/
public intindexOf(Object o) {int index = 0;if (o == null) {for (Node x = first; x != null; x =x.next) {if (x.item == null)returnindex;
index++;
}
}else{for (Node x = first; x != null; x =x.next) {if(o.equals(x.item))returnindex;
index++;
}
}return -1;
}/*** 返回对象在list中最后一次出现的下标*/
public intlastIndexOf(Object o) {int index =size;if (o == null) {for (Node x = last; x != null; x =x.prev) {
index--;if (x.item == null)returnindex;
}
}else{for (Node x = last; x != null; x =x.prev) {
index--;if(o.equals(x.item))returnindex;
}
}return -1;
}//Queue operations.队列的相关操作,先进先出
/*** 返回list第一个元素,没有元素不会报错*/
publicE peek() {final Node f =first;return (f == null) ? null: f.item;
}/*** 返回list中第一个元素,list为空会报错*/
publicE element() {returngetFirst();
}/*** 返回并删除list中第一个元素,list为空不会报错*/
publicE poll() {final Node f =first;return (f == null) ? null: unlinkFirst(f);
}/*** 删除并返回第一个list中的元素,list为空会报错*/
publicE remove() {returnremoveFirst();
}/*** 新增一个元素到list尾部*/
public booleanoffer(E e) {returnadd(e);
}//Queue operations end//Deque operations 双端队列的 一些操作
/*** 在队列的 最前端加入一个元素*/
public booleanofferFirst(E e) {
addFirst(e);return true;
}/*** 在队列的 最后端加入一个元素*/
public booleanofferLast(E e) {
addLast(e);return true;
}/*** 获取队列的第一个元素*/
publicE peekFirst() {final Node f =first;return (f == null) ? null: f.item;
}/*** 获取队列的最后一个元素*/
publicE peekLast() {final Node l =last;return (l == null) ? null: l.item;
}/*** 返回并删除队列中的第一个元素*/
publicE pollFirst() {final Node f =first;return (f == null) ? null: unlinkFirst(f);
}/*** 返回并删除队列中的最后一个元素*/
publicE pollLast() {final Node l =last;return (l == null) ? null: unlinkLast(l);
}//Deque operations end//stack operations 出栈和入栈的 一些相关操作。
/*** 向栈中压入一个元素*/
public voidpush(E e) {
addFirst(e);
}/*** 从栈中弹出一个元素,栈为空会报错*/
publicE pop() {returnremoveFirst();
}//stack operations end
/*** 删除该对象第一次出现的节点*/
public booleanremoveFirstOccurrence(Object o) {returnremove(o);
}/*** 删除该对象最后一个出现的节点*/
public booleanremoveLastOccurrence(Object o) {if (o == null) {for (Node x = last; x != null; x =x.prev) {if (x.item == null) {
unlink(x);return true;
}
}
}else{for (Node x = last; x != null; x =x.prev) {if(o.equals(x.item)) {
unlink(x);return true;
}
}
}return false;
}/*** 获取list迭代器*/
public ListIterator listIterator(intindex) {
checkPositionIndex(index);return newListItr(index);
}private class ListItr implements ListIterator{private NodelastReturned;private Nodenext;private intnextIndex;private int expectedModCount =modCount;
ListItr(intindex) {//assert isPositionIndex(index);
next = (index == size) ? null: node(index);
nextIndex=index;
}public booleanhasNext() {return nextIndex
}publicE next() {
checkForComodification();if (!hasNext())throw newNoSuchElementException();
lastReturned=next;
next=next.next;
nextIndex++;returnlastReturned.item;
}public booleanhasPrevious() {return nextIndex > 0;
}publicE previous() {
checkForComodification();if (!hasPrevious())throw newNoSuchElementException();
lastReturned= next = (next == null) ?last : next.prev;
nextIndex--;returnlastReturned.item;
}public intnextIndex() {returnnextIndex;
}public intpreviousIndex() {return nextIndex - 1;
}public voidremove() {
checkForComodification();if (lastReturned == null)throw newIllegalStateException();
Node lastNext =lastReturned.next;
unlink(lastReturned);if (next ==lastReturned)
next=lastNext;elsenextIndex--;
lastReturned= null;
expectedModCount++;
}public voidset(E e) {if (lastReturned == null)throw newIllegalStateException();
checkForComodification();
lastReturned.item=e;
}public voidadd(E e) {
checkForComodification();
lastReturned= null;if (next == null)
linkLast(e);elselinkBefore(e, next);
nextIndex++;
expectedModCount++;
}public void forEachRemaining(Consumer super E>action) {
Objects.requireNonNull(action);while (modCount == expectedModCount && nextIndex
action.accept(next.item);
lastReturned=next;
next=next.next;
nextIndex++;
}
checkForComodification();
}final voidcheckForComodification() {if (modCount !=expectedModCount)throw newConcurrentModificationException();
}
}//节点类,静态内部类,用来作为LinkedList内部的节点
private static class Node{
E item;
Nodenext;
Nodeprev;
Node(Node prev, E element, Nodenext) {this.item =element;this.next =next;this.prev =prev;
}
}/*** 逆向迭代器,只能从后往前迭代
*@since1.6*/
public IteratordescendingIterator() {return newDescendingIterator();
}/*** Adapter to provide descending iterators via ListItr.previous*/
private class DescendingIterator implements Iterator{private final ListItr itr = newListItr(size());public booleanhasNext() {returnitr.hasPrevious();
}publicE next() {returnitr.previous();
}public voidremove() {
itr.remove();
}
}
@SuppressWarnings("unchecked")private LinkedListsuperClone() {try{return (LinkedList) super.clone();
}catch(CloneNotSupportedException e) {throw newInternalError(e);
}
}/*** 浅克隆方法*/
publicObject clone() {
LinkedList clone =superClone();//Put clone into "virgin" state
clone.first = clone.last = null;
clone.size= 0;
clone.modCount= 0;//Initialize clone with our elements
for (Node x = first; x != null; x =x.next)
clone.add(x.item);returnclone;
}/*** 得到一个包含list所有元素的数组,长度为size*/
publicObject[] toArray() {
Object[] result= newObject[size];int i = 0;for (Node x = first; x != null; x =x.next)
result[i++] =x.item;returnresult;
}/*** 将list中的元素存到为数组a中,如果a的长度不否就从新反射构建一个长度为size的数组,如果长度有多的,则就后面的都设置为null*/@SuppressWarnings("unchecked")public T[] toArray(T[] a) {if (a.length
a=(T[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);int i = 0;
Object[] result=a;for (Node x = first; x != null; x =x.next)
result[i++] =x.item;if (a.length >size)
a[size]= null;returna;
}private static final long serialVersionUID = 876323262645176354L;/*** 将list实例保存到流中*/
private voidwriteObject(java.io.ObjectOutputStream s)throwsjava.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 x = first; x != null; x =x.next)
s.writeObject(x.item);
}/*** 从流中读取list实例*/@SuppressWarnings("unchecked")private voidreadObject(java.io.ObjectInputStream s)throwsjava.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());
}/*** 用来多线程并行迭代的迭代器,这个迭代器的主要作用就是把list分成了好几段,每个线程执行一段,因此是线程安全的。*/@Overridepublic Spliteratorspliterator() {return new LLSpliterator(this, -1, 0);
}/**A customized variant of Spliterators.IteratorSpliterator*/
static final class LLSpliterator implements Spliterator{static final int BATCH_UNIT = 1 << 10; //batch array size increment
static final int MAX_BATCH = 1 << 25; //max batch array size;
final LinkedList list; //null OK unless traversed
Node current; //current node; null until initialized
int est; //size estimate; -1 until first needed
int expectedModCount; //initialized when est set
int batch; //batch size for splits
LLSpliterator(LinkedList list, int est, intexpectedModCount) {this.list =list;this.est =est;this.expectedModCount =expectedModCount;
}final intgetEst() {int s; //force initialization
final LinkedListlst;if ((s = est) < 0) {if ((lst = list) == null)
s= est = 0;else{
expectedModCount=lst.modCount;
current=lst.first;
s= est =lst.size;
}
}returns;
}public long estimateSize() { return (long) getEst(); }public SpliteratortrySplit() {
Nodep;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= newObject[n];int j = 0;do { a[j++] = p.item; } while ((p = p.next) != null && j
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 p; intn;if (action == null) throw newNullPointerException();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 newConcurrentModificationException();
}public boolean tryAdvance(Consumer super E>action) {
Nodep;if (action == null) throw newNullPointerException();if (getEst() > 0 && (p = current) != null) {--est;
E e=p.item;
current=p.next;
action.accept(e);if (list.modCount !=expectedModCount)throw newConcurrentModificationException();return true;
}return false;
}public intcharacteristics() {return Spliterator.ORDERED | Spliterator.SIZED |Spliterator.SUBSIZED;
}
}
}