1.LinkedList简介
LinkedList是一个实现了List接口和Deque接口的双端链表。 LinkedList底层的链表结构使它支持高效的插入和删除操作,另外它实现了Deque接口,使得LinkedList类也具有队列的特性
LinkedList不是线程安全的,如果想使LinkedList变成线程安全的,可以调用静态类Collections类中的synchronizedList方法:
List list = Collections.synchronizedList(new LinkedList<>());
与ArrayList不一样,LinkedList底层是链表(双向),其结点结构:
private static class Node<E> {
//存放元素
E item;
//指向下一个Node节点
Node<E> next;
//指向上一个Node节点
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
2.LinkedListDemo
这一部分主要是为了了解LinkedList常见API的用法,熟悉的朋友们可以直接跳过~
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
/*
增
public void addFirst(E e) //插入指定元素到列表首端
public void addLast(E e) //插入指定元素到列表尾端
public boolean add(E e) //尾端
public void add(int index, E element) //将指定元素element插入到原列表的index位置之前
//添加指定集合中的所有元素到列表的尾部
public boolean addAll(Collection<? extends E> c)
//将指定集合中的所有元素插入到列表中index-1与index之间
public boolean addAll(int index, Collection<? extends E> c)
*/
list.add("b");
list.add(0, "a");
list.addFirst("first");
list.addLast("last");
HashSet<String> sets = new HashSet<>();
sets.add("c");
sets.add("d");
sets.add("e");
list.addAll(3, sets);
System.out.println(list.toString());
/*
改
public E set(int index, E element) //使用指定元素替换指定位置的元素,返回原元素的值
*/
list.set(1, "aa");
System.out.println(list.toString());
/*
查
public boolean contains(Object o) //查看列表中是否包含指定元素
public E get(int index) //返回指定位置的元素
public E getFirst() // 返回列表的首节点
public E getLast() // 返回列表的尾节点
//从头-->尾遍历,返回指定元素第一次出现的位置,否则返回-1
public int indexOf(Object o)
//从尾-->头遍历,返回指定元素第一次出现的位置,否则返回-1,
//改方法的功能也可以理解为返回元素最后一次出现的位置
public int lastIndexOf(Object o)
*/
System.out.println("是否包含aa: " + list.contains("aa"));
System.out.println("index=1: " + list.get(1));
System.out.println("First: " + list.getFirst());
System.out.println("Last: " + list.getLast());
/*
遍历
使用foreach或者迭代器,但注意迭代器是一次性使用,每次使用都要新建
*/
System.out.print("使用foreach遍历: ");
for (String l : list) {
System.out.print(l + " ");
}
System.out.println();
System.out.print("使用迭代器遍历: ");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
/*
删
public E removeFirst() //移除并返回首节点
public E removeLast() //移除并返回尾节点
public boolean remove(Object o) //删除列表中首次出现的该指定元素
public E remove(int index) //移除列表指定位置的元素,并返回该元素
public E remove() //删除列表的头部First
//从头-->尾遍历,删除此队列中第一个出现的指定元素
public boolean removeFirstOccurrence(Object o)
//从尾-->头遍历,删除此队列中第一次出现的指定元素
public boolean removeLastOccurrence(Object o)
*/
list.removeFirst();
list.removeLast();
System.out.println(list.toString());
list.remove();
System.out.println(list.toString());
list.removeFirstOccurrence("c");
System.out.println(list.toString());
/*
* 在LinkedList中还有一个列表迭代器ListIterator
* 跟普通迭代器不一样的地方在于这个迭代器不仅可以正序遍历,
还可以使用previous方法进行倒序遍历,
DescendingIterator就是使用了迭代器的previous方法进行遍历的。
其方法除了hasNext()与next()外,还有:
public boolean hasPrevious()
public E previous()
public int nextIndex()
public int previousIndex()
public void remove()
public void set(E e)
public void add(E e)
*/
//-------------------------------------------------------------------
/*
除以上常用API外,LinkedList还提供了一些供队列结构使用的API:
*/
Queue<String> queue = new LinkedList();
/*
增(入队)
public void push(E e) //在队列头部插入元素
public boolean offer(E e) //添加指定元素到队列尾部
public boolean offerFirst(E e) //插入指定元素到队列首部
public boolean offerLast(E e) //插入指定元素到队列尾部
*/
/*
查
public E peek() //查看(不操作)此列表的头部元素。
public E peekFirst() //取回但是不删除队列的首元素。如果队列为空则返回null
public E peekLast() //取回但是不删除链表的最后一个元素,如果队列为空,则返回null
public E element() //取回但不删除此列表的头部(第一个元素)
*/
/*
删(出队)
public E pop() //删除并返回队列的第一个元素,如果列表为空则抛出NoSuchElementException异常
public E remove() //取回并删除此列表的头部(第一个元素)
public E poll() //返回并删除此列表的头部(第一个元素)
public E pollFirst() //取回并删除队列的首元素,如果队列为空,则返回null
public E pollLast() //取回并删除队列的尾元素,如果队列为空,则返回null
*/
}
}
输出:
[first, a, b, c, d, e, last]
[first, aa, b, c, d, e, last]
是否包含aa: true
index=1: aa
First: first
Last: last
使用foreach遍历: first aa b c d e last
使用迭代器遍历: first aa b c d e last
[aa, b, c, d, e]
[b, c, d, e]
[b, d, e]
3.LinkedList与ArrayList对比分析
根据上一篇文章我们知道,ArrayList的最大特点就是能随机访问,因为元素在物理上是连续存储的,所以访问的时候,可以通过简单的算法直接定位到指定位置,所以不管列表的元素数量有多少,总能在O(1)的时间里定位到指定位置,但是连续存储也是它的缺点,导致要在中间插入一个元素的时候,所有之后的元素都要往后挪动,需要进行更多的赋值操作,如果刚好需要扩容的话,那就会更慢了。而LinkedList只需要将插入位置的前后元素的next或prev引用进行调整即可,而且也没有扩容问题,因为它本身就没有容量的概念,理论上可以无限添加元素。
我们使用系统提供的计时器来比较以下两者的差别:
//自定义一个计时器,每个需要统计耗时的操作只需要继承该类,然后重写doSomeThing方法即可
public abstract class TimeCounter {
private String name;
TimeCounter(String name){
this.name = name;
}
public void count(){long time = System.currentTimeMillis();
doSomething();
System.out.println(name + " 耗时:" + (System.currentTimeMillis() - time));
}
protected abstract void doSomething();
}
3.1 元素插入到末尾的add操作的比较
public class Test {
public static void main(String[] args){
TimeCounter arrayListAddCounter = new TimeCounter("ArrayList add插入到末尾:") {
private List<Integer> list = new ArrayList<>();
@Override
protected void doSomething() {
for (int i = 0; i < 1000000; i++) {
list.add( i);
}
}
};
TimeCounter linkedListAddCounter = new TimeCounter("LinkedList add插入到末尾:") {
private List<Integer> list = new LinkedList<>();
@Override
protected void doSomething() {
for (int i = 0; i < 1000000; i++) {
list.add( i);
}
}
};
arrayListAddCounter.count();
linkedListAddCounter.count();
}
}
输出:
ArrayList add插入到末尾: 耗时:40
LinkedList add插入到末尾: 耗时:768
是不是很意外- - ,因为在ArrayList容量足够的情况下,ArrayList的插入元素到末尾操作是比LinkedList插入要快的,因为它只需要进行一次赋值即可,而LinkedList还需要先new一个新节点然后再接到链表的最后,这个new的过程看起来微不足道,但是一旦循环次数到达一定量级,开销是不可忽略的。接下来我们再来看看把元素插入到表首两者的差异。
3.2 元素插入到表首的add操作的比较:
public class Test {
public static void main(String[] args){
TimeCounter arrayListAddCounter = new TimeCounter("ArrayList add插入到首端:") {
private List<Integer> list = new ArrayList<>();
@Override
protected void doSomething() {
for (int i = 0; i < 100000; i++) {
list.add(0, i);
}
}
};
TimeCounter linkedListAddCounter = new TimeCounter("LinkedList add插入到首端:") {
private List<Integer> list = new LinkedList<>();
@Override
protected void doSomething() {
for (int i = 0; i < 100000; i++) {
list.add(0, i);
}
}
};
arrayListAddCounter.count();
linkedListAddCounter.count();
}
}
输出:
ArrayList add插入到首端: 耗时:607
LinkedList add插入到首端: 耗时:11
结果在意料之中,因为每次都插入在首端时,ArrayList需要进行大量元素移动,而且列表中元素越多,需要进行移动的次数也越多,在这种情况下,插入元素的效率,LinkedList是明显优于ArrayList的。
3.3 查找操作的比较
public class Test {
public static void main(String[] args){
TimeCounter arrayListAddCounter = new TimeCounter("ArrayList get遍历元素:") {
private List<Integer> list = new ArrayList<>();
{
for (int i = 0; i < 100000; i++) {
list.add(i);
}
}
@Override
protected void doSomething() {
for (int i = 0; i < 100000; i++) {
list.get(i);
}
}
};
TimeCounter linkedListAddCounter = new TimeCounter("LinkedList get遍历元素:") {
private List<Integer> list = new LinkedList<>();
{
for (int i = 0; i < 100000; i++) {
list.add(i);
}
}
@Override
protected void doSomething() {
for (int i = 0; i < 100000; i++) {
list.get(i);
}
}
};
arrayListAddCounter.count();
linkedListAddCounter.count();
}
}
输出:
ArrayList get遍历元素: 耗时:3
LinkedList get遍历元素: 耗时:4484
可见,LinkedList不支持随机访问,查找元素的效率比ArrayList要低得多,因为在LinkedList中每次get的时候都是从链表两端进行逐个查找,直到找到指定的位置,这是一个十分耗时的过程。
总体来说,ArrayList和LinkedList是各有所长,在实际运用中可以根据具体业务需求决定选用哪一种,如果是插入操作比较频繁,当然是选用LinkedList较好,如果是查找操作较多,则选用ArrayList更优。当然,这也是建立在数据量大于万级的基础上,一般数据量较小的情况下,两者的差异不会很明显。
4.LinkedList源码分析
以下是LinkedList全部源码(注释详细),比较简单,推荐整体阅读一下,能够对LinkedList有更好的掌握。
import java.util.*;
import java.util.function.Consumer;
/**
* 双向链表实现了List接口和Deque接口,实现了多有可选List操作,并且允许放入所有的元素,包括null。
*
* 注意,这个实现类不是线程安全的,如果多个线程同时访问一个链表,并且至少一个线程修改了链表的结构,
* 则必须在外部实现同步。结构性修改指的是那些增加删除一个或多个元素的操作,仅设置元素的值不是结构修改。
* 这通常通过在封装列表的某个对象上进行同步来实现。
*
* 如果没有这样的对象存在,则列表应该使用Collections.synchronizedList方法包装,最好在创建列表的时候进行,
* 以防止意外的非同步引用对列表进行了修改。
* List list = Collections.synchronizedList(new LinkedList(...));
*
* 该类的iterator方法和listIterator方法返回的迭代器是“fail-fast”的,如果列表在迭代器创建之后的任何时刻发生结构性的修改了,则调用迭代器自身的remove或者add方法时将会抛出ConcurrentModificationException异常,因此当遇到并发修改时,迭代器会快速的失败,而不是在未来某个不确定的时刻进行武断冒险或不确定性的行为
*
* 注意,通常来说,不能保证迭代器的fail-fast机制,在遇非同到步的并发修改时,不可能做出任何严格的保证。
* fail-fast 迭代器只能尽最大努力抛出ConcurrentModificationException异常,因此,如果程序依赖这个异常来
* 进行正确性判断是错误的,fail-fast机制应该仅用于检测异常。
*/
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable {
transient int size = 0;
/**
* 指向第一个节点
* 恒等式: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* 指向最后一个节点
* 恒等式: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
/**
* 构造一个空的列表
*/
public LinkedList() {
}
/**
* 构造一个包含指定集合内所有元素的列表,存储的顺序为集合的迭代器访问顺序。
* * @throws NullPointerException 空指针异常
*/
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;
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) {
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;
}
/**
* 移除非空节点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;
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);
}
/**
* 返回列表中是否包含指定元素
*/
public boolean contains(Object o) {
return indexOf(o) != -1;
}
/**
* 返回列表中元素个数
*/
public int size() {
return size;
}
/**
* 添加指定元素到列表尾部
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* 如果该元素存在,则移除列表中首次出现的该指定元素,如果不存在,则原链表不会改变。
* 如果该列表中包含该指定元素则返回true,否则返回false
*/
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;
}
/**
* 添加指定集合中的所有元素到列表的尾部,顺序为指定集合的迭代器遍历顺序。如果该操作正在进行时,指定集合
* 被修改了,那么该操作的行为是不可预测的。
*/
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
/**
* 将指定集合中的所有元素插入到列表中index-1与index之间
*/
public boolean addAll(int index, Collection<? extends E> c) {
checkPositionIndex(index);
Object[] a = c.toArray();
//numNew表示插入元素的个数
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;
}
//将集合中的元素连接到pred之后
for (Object o : a) {
@SuppressWarnings("unchecked") E e = (E) o;
Node<E> newNode = new Node<>(pred, e, null);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
//将index处及之后的元素与刚插入的部分连接起来
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
/**
* 移除列表中所有元素
*/
public void clear() {
// 清除节点之间所有元素的链接不是必要的,但是:
// - 如果被清除的节点处于不同代之间,可以帮助分代GC。
// - 一定要释放内存,即便有一个迭代器引用
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++;
}
// 位置访问操作
/**
* 返回指定位置的元素
*/
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;
}
/**
* 将指定元素element插入到原列表的index位置之前
*/
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
/**
* 移除列表指定位置的元素
* 返回列表中移除的元素。
*/
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/**
* 判断index下标是否是合法位置
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
/**
* 返回IndexOutOfBoundsException 异常的错误信息
*/
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);
//做了一个小优化,如果取的序号小于元素个数的一半,则从链表首端开始遍历,否则从链表尾部开始遍历
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;
}
}
// 搜索操作
/**
* 返回指定元素在列表中第一次出现的位置,否则返回-1
*/
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;
}
/**
* 返回指定元素在链表中最后一次出现的位置,如果链表中不包含该元素,则返回-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;
}
// 队列操作
/**
* 查看(不操作)此列表的头部元素。
*/
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* 取回但不删除此列表的头部(第一个元素)。
* 如果不存在,则会抛出NoSuchElementException异常
*/
public E element() {
return getFirst();
}
/**
* 返回并删除此列表的头部(第一个元素)。
* 如果该链表为空,则返回null
*/
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* 取回并删除此列表的头部(第一个元素)。
*/
public E remove() {
return removeFirst();
}
/**
* 添加指定元素到链表尾部
*/
public boolean offer(E e) {
return add(e);
}
// 双向队列操作
/**
* 插入指定元素到队列首部
*/
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
/**
* 插入指定元素到队列尾部
*/
public boolean offerLast(E e) {
addLast(e);
return true;
}
/**
*
* 取回但是不删除队列的首元素。如果队列为空则返回null。
*/
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
/**
* 取回但是不删除链表的最后一个元素,如果队列为空,则返回null
*/
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
/**
* 取回并删除队列的首元素,如果队列为空,则返回null
*/
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
/**
* 取回并删除队列的尾元素,如果队列为空,则返回null
*/
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
/**
* 在队列头部插入元素
*/
public void push(E e) {
addFirst(e);
}
/**
* 删除并返回队列的第一个元素,如果列表为空则抛出NoSuchElementException 异常
*/
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”的,如果列表在迭代器创建之后的任何时刻被进行
* 结构性的修改了,则调用迭代器自身的remove或者add方法时将会抛出ConcurrentModificationException异常,因此
* 当遇到并发修改时,迭代器会快速的失败,而不是在未来某个不确定的时刻进行武断冒险或不确定性的行为
*
* 注意,通常来说,不能保证迭代器的fail-fast机制,在遇到非同步的并发修改时,不可能做出任何严格的保证。
* fail-fast 迭代器只能尽最大努力抛出ConcurrentModificationException异常,因此,如果程序依赖这个异常来
* 进行正确性判断是错误的,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;
//用于检测遍历过程中List是否被修改
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;
}
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;
}
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节点
Node<E> next;
//指向上一个Node节点
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
/**
* 返回一个倒序遍历的迭代器
*/
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();
}
}
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.first = clone.last = null;
clone.size = 0;
clone.modCount = 0;
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;
}
/**
* 返回一个包含列表所有元素的数组,元素的顺序为从第一个到最后一个。返回元素数组的类型
* 与指定数组的类型一致。如果列表大小适合指定的数组,则返回该数组。 否则,将为新数组分配指定
* 数组的运行时类型和此列表的大小。
*
* 如果列表的空间适合指定的数组(数组比列表有更多的元素),紧跟在列表末尾之后的数组中的元素设置
* 为null(仅当调用者知道列表不包含任何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;
/**
* 序列化
*/
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);
}
/**
* 反序列化
*/
@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);
}
/** Spliterators.IteratorSpliterator 的定制版本 */
static final class LLSpliterator<E> implements Spliterator<E> {
static final int BATCH_UNIT = 1 << 10; // batch array size increment
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
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(); }
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;
}
}
}