目录
增加节点 linkFirst,linkLast,linkBefore
删除节点 unlinkFirst,unlinkLast,unlink
查找 node,checkXXXIndex,isXXXIndex
Queue的方法 remove,element,offer,poll,peek
查找 contains,size,indexOf,lastIndexOf
两个add,两个remove,两个addAll,get,set,clear
逆向迭代器 descendingIterator 和内部类 DescendingIterator
其余 clone,两个toArray,writeObject,readObject
spliterator和 内部类 LLSpliterator
简介
/**
* <p>双链表,实现了List和Deque接口。
* 实现了所有的可选列表操作,允许所有的元素(包括null)
*
* <p>所有的操作都符合双链表的预期。
* 对于指向列表下标的操作,会遍历列表,从头开始或者从尾开始,取决于哪个与指定index更近。
*
* <p>注意:这个实现是不同步的。
* 如果多线程并发地访问一个linkedlist,并且至少一个线程结构上修改了列表,必须在外部进行同步。
* (结构上的改变是增加,删除一个或多个元素,
* 或者显式地改变依赖数组的大小,仅仅改变元素的值不会是一个结构上的改变)
* 这通常是对封装列表的对象进行同步,来完成。
* 如果没有这样的对象,列表应该使用Collections.synchronizedList来包装它。
* 它通常该在创建时做,来防止意外对列表的非同步访问。
* <pre>
* List list = Collections.synchronizedList(new LinkedList(...));</pre>
*
* <p>返回的Iterator和ListIterator是快速失败的。
* 如果Iterator创建后,列表在任何时间被结构上改变了,
* 除了迭代器自己的remove和add方法外,迭代器会抛出ConcurrentModificationException。
* 因此,面对并发的改变,Iterator快速失败,十分干净,
* 而不是在将来某个不确定的时间,冒着风险,做任意的,不确定性的操作。
*
* <p>注意:不能保证Iterator的快速失败机制,
* 因为,通常地说,在存在非同步的并发修改的情况下,不可能做出严格的保证。
* 快速失败的迭代器基于最大努力抛出ConcurrentModificationException。
* 因此,依赖于这个异常,写程序来保证正确性是错的,
* 迭代器的快速失败机制,应该仅仅被用来探测bug
*
*
* @author Josh Bloch
* @see List
* @see ArrayList
* @since 1.2
* @param <E> the type of elements held in this collection
*/
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
内部类
内部类 Node
/** 私有的静态内部类,节点类
* @author xusy
*
* @param <E>
*/
private static class Node<E> {
//这三个字段的权限修饰符是默认的,只在Linkedlist和它的内部类中,直接使用
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;
}
}
字段 size,first,last
/**
* 链表的长度,初始为0
*/
transient int size = 0;
/**
* 指向第一个节点
* 不变的: (first == null && last == null) ||
* (first.prev == null && first.item != null)
* <p> 链表为空时,first和last都为null。
* 不为空时,first不为null,first.item不为null,first.prev为null
*/
transient Node<E> first;
/**
* 指向最后一个节点
* 不变的: (first == null && last == null) ||
* (last.next == null && last.item != null)
* <p> 链表为空时,first和last都为null。
* 不为空时,last不为null,last.item不为null,last.next为null
*/
transient Node<E> last;
构造器 无参,Collection
/**
* 创建一个空列表
*/
public LinkedList() {
}
/**
* 创建一个包含指定集合元素的列表,顺序为集合迭代器返回的顺序。
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public LinkedList(Collection<? extends E> c) {
this(); // 先创建一个空列表
addAll(c); //再将c的东西全部加入
}
可以看到linkedList没有构造器参数为int的构造方法,一般只用无参构造器,啥都不干,让size默认为0,first和last也默认为0。当add的时候, 会调用linkLast方法,创建节点,给first和last赋值
内部方法
增加节点 linkFirst,linkLast,linkBefore
/**
* 将e作为头结点,设置头结点.
* <p> 链表内的操作,主要涉及链表内的first,last,新的节点,新的节点的前后,总共5个地方!!!
*/
private void linkFirst(E e) {
final Node<E> f = first;
// 设置新节点,prev=null,next=first
final Node<E> newNode = new Node<>(null, e, f);
// 设置链表内的first
first = newNode;
//处理链表内的last节点,和原来first节点的prev
//如果链表为空,无须处理原来first节点的prev,设置last
//如果链表不为空,无须处理last,设置原来first节点的prev
if (f == null)
last = newNode;
else
f.prev = newNode;
//size和modeCount++
size++;
modCount++;
}
/**
* 将e作为尾结点,设置尾结点
*/
void linkLast(E e) {
final Node<E> l = last;
// 设置新节点,prev=last,next=null
final Node<E> newNode = new Node<>(l, e, null);
// 设置last
last = newNode;
//设置first和原来last的next
if (l == null)
first = newNode;
else
l.next = newNode;
//size和modeCount++
size++;
modCount++;
}
/**
* 在非空节点succ前,插入元素e
*/
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;
//设置新节点的前面节点,和first节点
if (pred == null)
first = newNode;
else
pred.next = newNode;
size++;
modCount++;
}
删除节点 unlinkFirst,unlinkLast,unlink
/**
* 删除非空的头结点f
*/
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
first = next;
// 处理last和自身的后面节点
if (next == null)
last = null;
else
next.prev = null;
size--;
modCount++;
return element;
}
/**
* 删除非空的尾节点l
*/
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
last = prev;
//处理first和自身的前面节点
if (prev == null)
first = null;
else
prev.next = null;
size--;
modCount++;
return element;
}
/**
* 删除非空节点x
*/
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;
// 处理first
// 处理prev和自身
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
// 处理last
// 处理next和自身
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
// 处理自身
x.item = null;
size--;
modCount++;
return element;
}
查找 node,checkXXXIndex,isXXXIndex
/**
* 确认参数是否是一个已经存在的元素的index [0,size)
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/**
* 确认参数是否是对于Iterator或者add操作,合法的位置的index [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;
}
/**
* 确认参数是否是一个已经存在的元素的index [0,size)
*/
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 确认参数是否是对于Iterator或者add操作,合法的位置的index [0,size]
*/
private void checkPositionIndex(int index) {
if (!isPositionIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 返回指定index上的非空节点。从first或者last开始找到该节点
*/
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) { // 如果index < size/2
Node<E> x = first;
for (int i = 0; i < index; i++) //从first开始找
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--) //从last开始找
x = x.prev;
return x;
}
}
Queue的方法 remove,element,offer,poll,peek
/**
* 返回,但不删除列表的头部(第一个元素)。
* 如果列表为空,返回null。
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* 返回,但不删除列表的头部(第一个元素)。
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E element() {
return getFirst();
}
/**
* 返回,并删除列表的头部(第一个元素)。
* 如果列表为空,返回null。
*
* @return the head of this list, or {@code null} if this list is empty
* @since 1.5
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* 返回,并删除列表的头部(第一个元素)。
*
* @return the head of this list
* @throws NoSuchElementException if this list is empty
* @since 1.5
*/
public E remove() {
return removeFirst();
}
/**
* 加入指定元素,作为列表的尾部(最后一个元素)
*
* @param e the element to add
* @return {@code true} (as specified by {@link Queue#offer})
* @since 1.5
*/
public boolean offer(E e) {
return add(e);
}
Deque方法
getXXX,removeXXX,addXXX
//Deque里的6个方法,操作失败抛出异常
/**
* 返回列表的第一个元素。操作失败抛出异常
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
// 为空抛出异常
throw new NoSuchElementException();
return f.item;
}
/**
* 返回列表的最后一个元素。操作失败抛出异常
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
/**
* 删除并返回列表的第一个元素。操作失败抛出异常
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* 删除并返回列表的最后一个元素。操作失败抛出异常
*
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* 插入指定元素到列表头部,因为是linkedlist,不会插入失败
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* 插入指定元素到列表尾部,因为是linkedlist,不会插入失败
*
* <p>方法与 {@link #add} 相同
*
* @param e the element to add
*/
public void addLast(E e) {
linkLast(e);
}
offerXXX,pollXXX,peekXXX
// Deque 操作
/**
* 插入指定元素到列表头部。
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerFirst})
* @since 1.6
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
/**
* 插入指定元素到列表尾部。
*
* @param e the element to insert
* @return {@code true} (as specified by {@link Deque#offerLast})
* @since 1.6
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}
/**
* 返回,但是不删除列表的第一个元素。
* 或者,如果列表为空,它返回null。
*
* @return the first element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* 返回,但是不删除列表的最后一个元素。
* 或者,如果列表为空,它返回null。
*
* @return the last element of this list, or {@code null}
* if this list is empty
* @since 1.6
*/
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
/**
* 返回,并删除列表的第一个元素。
* 或者,如果列表为空,它返回null。
*
* @return the first element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* 返回,并删除列表的最后一个元素。
* 或者,如果列表为空,它返回null。
*
* @return the last element of this list, or {@code null} if
* this list is empty
* @since 1.6
*/
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
Deque里的栈 push,pop
// 栈的操作
/**
* 推入指定元素到由列表代表的栈(换言而之,在列表的头部)
*
* <p>方法与 {@link #addFirst} 相同
*
* @param e the element to push
* @since 1.6
*/
public void push(E e) {
addFirst(e);
}
/**
* 弹出指定元素到由列表代表的栈(换言而之,在列表的头部)
*
* <p>方法与 {@link #removeFirst} 等价
*
* @return the element at the front of this list (which is the top
* of the stack represented by this list)
* @throws NoSuchElementException if this list is empty
* @since 1.6
*/
public E pop() {
return removeFirst();
}
removeXXXOccurence
/**
* 删除这个列表的第一次遇到的指定元素。(当遍历列表从头到尾)
* 如果不包含这个元素,它不改变。
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
/**
* 删除这个列表的最后一次遇到的指定元素。(当遍历列表从头到尾)
* 如果不包含这个元素,它不改变。
*
* @param o element to be removed from this list, if present
* @return {@code true} if the list contained the specified element
* @since 1.6
*/
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;
}
列表
查找 contains,size,indexOf,lastIndexOf
/**
* 如果这个列表包含指定的元素,返回true。
* 更正式地,返回true,当且仅当列表包含至少一个这样的元素e,
* <tt>(o==null ? e==null : o.equals(e))</tt>
*
* @param o element whose presence in this list is to be tested
* @return {@code true} if this list contains the specified element
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* 返回列表中元素的数量。
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
/**
* 返回列表中第一次出现指定元素的位置,或者如果列表中不包含这个元素,返回-1。
* 更正式地,返回最小的index i,
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* 或者如果没有这样的index,返回-1
*
* @param o element to search for
* @return the index of the first occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
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) { // 从first开始往后找
if (o.equals(x.item))
return index;
index++;
}
}
return -1;
}
/**
* 返回列表中最后一次出现指定元素的位置,或者如果列表中不包含这个元素,返回-1。
* 更正式地,返回最大的index i,
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* 或者如果没有这样的index,返回-1
*
* @param o element to search for
* @return the index of the last occurrence of the specified element in
* this list, or -1 if this list does not contain the element
*/
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) { // 从last开始往前找
index--;
if (o.equals(x.item))
return index;
}
}
return -1;
}
两个add,两个remove,两个addAll,get,set,clear
/**
* 插入指定元素到列表尾部,因为是linkedlist,不会插入失败
*
* <p>方法与 {@link #addLast} 相同
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* 如果指定元素存在,从列表中移除指定元素。
* 更正式地说,移除一个index最小的这样的元素(如果这样的元素存在) ,
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
* 如果列表包含指定元素,返回true。(如果列表因为调用而改变,返回true)
*
* @param o element to be removed from this list, if present
* @return {@code true} if this list contained the specified element
*/
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 {
// 从first开始,不断找
for (Node<E> x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
/**
* 将指定列表的所有元素加入到这个列表的最后,顺序为指定列表的迭代器的返回顺序。
* 当执行操作时,如果修改指定列表,操作的结果未知。
* (这意味着,如果如果指定列表是这个列表,而且列表是非空的,调用的结果未知)
*
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(Collection<? extends E> c) {
// 在size处,加入
return addAll(size, c);
}
/**
* 将指定列表的所有元素加入到这个列表的指定位置。
* 在这个位置的元素(如果有)和任何这个元素右边的元素,被移动到右边(增加它们的index)
* 新的元素出现的顺序为指定集合的迭代器的返回顺序。
*
* @param index index at which to insert the first element
* from the specified collection
* @param c collection containing elements to be added to this list
* @return {@code true} if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
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和每次插入的前面
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
// 插入完后,设置last和最后插入元素,和succ
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
/**
* 移除列表中所有的元素。这个方法返回后,列表为空。
*/
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;
// 设置自身的item,next,prev
x.item = null;
x.next = null;
x.prev = null;
x = next;
}
// 设置first,next
first = last = null;
size = 0;
modCount++;
}
// 基于位置操作
/**
* 返回列表中指定位置的元素。
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
/**
* 用指定元素替代列表中指定位置的元素
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
// 得到节点后,重新设置item
E oldVal = x.item;
x.item = element;
return oldVal;
}
/**
* 插入指定元素到列表的指定位置。
* 在这个位置的元素(如果有)和任何后边的元素被移动到右边(将它们的index+1)
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
// 找到指定index的元素,在它前面插入元素
linkBefore(element, node(index));
}
/**
* 删除列表中指定位置的元素
* 移动后面的元素到左边(index-1)。
* 返回被移除的元素。
*
* @param index the index of the element to be removed
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
checkElementIndex(index);
// 删除index节点
return unlink(node(index));
}
迭代器 ListIterator和内部类ListItr
/**
* 返回一个覆盖列表中元素的ListIterator(以适当的顺序),
* 以列表中指定位置开始。
* 遵循List.listIterator(int) 的通用约定。
*
* <p>这个ListIterator是快速失败的:如果Iterator创建后,列表在任何时间被结构上改变了,
* 除了迭代器自己的remove和add方法外,迭代器会抛出ConcurrentModificationException。
* 因此,面对并发的改变,Iterator快速失败,十分干净,
* 而不是在将来某个不确定的时间,冒着风险,做任意的,不确定性的操作。
*
* @param index index of the first element to be returned from the
* list-iterator (by a call to {@code next})
* @return a ListIterator of the elements in this list (in proper
* sequence), starting at the specified position in the list
* @throws IndexOutOfBoundsException {@inheritDoc}
* @see List#listIterator(int)
*/
public ListIterator<E> listIterator(int index) {
checkPositionIndex(index);
return new ListItr(index);
}
private class ListItr implements ListIterator<E> {
// 上一次返回的节点,默认为null
private Node<E> lastReturned;
// 下次调用next返回的节点
private Node<E> next;
// 下次调用next返回的节点的index
private int nextIndex;
private int expectedModCount = modCount;
ListItr(int index) {
// assert isPositionIndex(index);
// next为列表中下标为index的元素,如果到最后,为null
next = (index == size) ? null : node(index);
// 设置nextIndex
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
checkForComodification();
if (!hasNext())
throw new NoSuchElementException();
// 设置lastReturned
lastReturned = next;
// next前进
next = next.next;
nextIndex++;
return lastReturned.item;
}
public boolean hasPrevious() {
return nextIndex > 0;
}
public E previous() {
checkForComodification();
if (!hasPrevious())
throw new NoSuchElementException();
// next为null,next为last,否则为next的prev
// lastReturned = next
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
public void remove() {
checkForComodification();
if (lastReturned == null)
// 如果为null,报错
throw new IllegalStateException();
Node<E> lastNext = lastReturned.next;
// 删除lastReturned
unlink(lastReturned);
// 设置next
if (next == lastReturned)
// 刚刚调用了previous
next = lastNext;
else
// 刚刚调用next
nextIndex--;
lastReturned = null;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
public void add(E e) {
checkForComodification();
lastReturned = null;
// 在next前加入e
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.next;
nextIndex++;
}
checkForComodification();
}
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
逆向迭代器 descendingIterator 和内部类 DescendingIterator
/**
* @since 1.6
*/
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
/**
* 适配器模式,提供反向的Iterator,通过ListItr.previous
*/
private class DescendingIterator implements Iterator<E> {
// 从最后开始
private final ListItr itr = new ListItr(size());
public boolean hasNext() {
return itr.hasPrevious();
}
public E next() {
// next为内部itr的previous
return itr.previous();
}
public void remove() {
itr.remove();
}
}
其余 clone,两个toArray,writeObject,readObject
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
// 调用Object的clone方法,进行浅拷贝
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/**
* 返回linkedlist的浅拷贝。(元素自身没有被复制)
*
* @return a shallow copy of this {@code LinkedList} instance
*/
public Object clone() {
// 调用Object的clone方法,进行浅拷贝
LinkedList<E> clone = superClone();
// 将clone变成初始状态
// 设置4个基本字段为0或null
clone.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
// 用我们的元素初始化clone
for (Node<E> x = first; x != null; x = x.next)
// clone中一个个加入自己的元素
clone.add(x.item);
return clone;
}
/**
* 返回一个包含这个列表所有元素的数组。(从第一个到最后一个元素)
*
* <p>返回的数组是安全的,因为列表没有维持对它的引用
* (换言而之,这个方法必须分配一个新的数组,即使列表内部已经有一个数组了)。
* 因此调用者修改返回的数组是安全的。
*
* <p>这个方法是基于数组和基于列表的API之间的桥梁。
*
* @return an array containing all of the elements in this list
* in proper sequence
*/
public Object[] toArray() {
// size大小的数组
Object[] result = new Object[size];
int i = 0;
for (Node<E> x = first; x != null; x = x.next)
// 每格为linkedlist内部不断递进的元素
result[i++] = x.item;
return result;
}
/**
* <p>返回一个包含这个列表所有元素的数组。(从第一个到最后一个元素)
* 返回的数组的运行时类型是指定数组的类型。
* 如果列表适合这个指定的数组的大小,她就在里面返回。
* 否则,创建一个新数组,类型为指定数组的运行时类型,大小为这个列表的大小。
*
* <p>如果该列表适应指定的数组,有着剩余的空间(数组比列表有更多的元素),
* 数组中的元素在列表的末尾的,被设置为null。
* (如果调用者知道列表确实没有任何null元素,这才有助于决定列表的长度)
*
* <p>像toArray()方法,这个方法作为基于数组和基于列表的API之间的桥梁。
* 此外,这个方法允许对输出的数组的运行时类型做出精确的控制。
* 在某些情况下,可能有助于减少分配的成本。
*
* <p>假设x是一个只能包含string的列表。
* 下面的代码能用于将列表放入一个新分配的string数组。
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* 注意:toArray(new Object[0])等价于toArray()的功能
*
* @param a the array into which the elements of the list are to
* be stored, if it is big enough; otherwise, a new array of the
* same runtime type is allocated for this purpose.
* @return an array containing the elements of the list
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this list
* @throws NullPointerException if the specified array is null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// 如果大小不够,生成T类型的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;
// 将剩余的格子变成null
if (a.length > size)
a[size] = null;
return a;
}
private static final long serialVersionUID = 876323262645176354L;
/**
* 保存linkedlist实例的状态,到一个流。(序列化)
*
* @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);
}
/**
* 从流中,重组一个linkedlist实例(反序列化)
*/
@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());
}
spliterator和 内部类 LLSpliterator
/**
* 创建一个覆盖列表元素的spliterator,是迟绑定和快速失败的
*
* <p>这个spliterator报告是SIZED,ORDERED。
* 覆盖的实现应该报告额外的特征值。
*
* <p>实现的spliterator额外报告了SUBSIZED,并且实现了trySplit方法,来允许有限的并发
*
* @return a {@code Spliterator} over the elements in this list
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new LLSpliterator<E>(this, -1, 0);
}
/** Spliterators.IteratorSpliterator 的特定变体 */
static final class LLSpliterator<E> implements Spliterator<E> {
static final int BATCH_UNIT = 1 << 10; // batch 数组每次增加的大小
static final int MAX_BATCH = 1 << 25; // batch 数组最大的长度
final LinkedList<E> list; // null OK 除非遍历
Node<E> current; // 当前的节点;null 直到初始化
int est; // 预计的大小 ; -1 直到第一次需要
int expectedModCount; // 当设置est时,初始化
int batch; // 分割的batch的大小(每次分割会增加BATCH_UNIT)
LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
// return new LLSpliterator<E>(this, -1, 0);
this.list = list;
this.est = est; // 初始 -1
this.expectedModCount = expectedModCount; // 初始 0
}
/** 返回预估要处理的元素的数量。
* 如果是初始化,设置current和est和expectedModCount字段
* @return
*/
final int getEst() {
int s; // 强制初始化
final LinkedList<E> lst;
if ((s = est) < 0) { // est初始为-1,此时要初始化
if ((lst = list) == null)
s = est = 0;
else {
// 设置current和est和expectedModCount字段
expectedModCount = lst.modCount;
current = lst.first;
s = est = lst.size; // linkedlist的size
}
}
return s;
}
public long estimateSize() { return (long) getEst(); }
public Spliterator<E> trySplit() {
Node<E> p;
int s = getEst();
if (s > 1 && (p = current) != null) { //如果有剩余的元素,而且current不为null
int n = batch + BATCH_UNIT; // 此次batch的大小,每次递增BATCH_UNIT
if (n > s)
n = s;
if (n > MAX_BATCH)
n = MAX_BATCH;
// 长度最后为预估元素长度或者n或者MAX_BATCH
Object[] a = new Object[n];
int j = 0;
//将数组a中放入current不断next的结果
do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
// 实际加入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<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); // 从current开始,不断next,直到为null
}
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; // current进行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;
}
}