版权声明:欢迎转载,转载请标明来源 https://blog.csdn.net/weixin_41973131/article/details/88951411
一 简介
LikedList实现了List跟Deque接口,并且实现了所有可选择的list操作。同时允许存储所有的元素(包括空值)
由于HashSet的迭代器消耗的时间与HashSet实例元素的大小成正比,再加上capacity容量是依靠HashMap进行实现的,因此在迭代器的效率需要得到重视的情况下,请不要设置太大的初始容量以及太小的加载因子
HashSet并没有实现同步,因此在多条线程操作HashSet并且存在对数据进行修改的情况下,需要在HashSet的外部进行同步处理。
在迭代器Iterator被创建后,如果此时对HashMap进行结构性的操作(add、remove),则会抛出ConcurrentModificationException异常,除非是调用Iterator的remove方法。
可以看到LinkedList类实现了List,Deque,并且是一个Doubly-linked list双向链表。支持克隆以及序列化。
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
}
二 成员变量
// LinkedList集合的元素数量
transient int size = 0;
// 指向第一个元素结点
transient Node<E> first;
// 指向最后一个元素结点
transient Node<E> last;
// 结点
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;
}
}
三 构造函数
// 构造一个空的LinkedList
public LinkedList() {
}
// 构造一个包含指定集合元素的list,按照集合类的迭代器输出排序
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++;
}
// 将元素e插入到非空的结点succ之前
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++;
}
// 解除非空的第一个结点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 = next;
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 = 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;
}
// 返回list的第一个元素
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
// 返回list的最后一个元素
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
// 移除并且返回list中的第一个元素
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
// 移除并返回list中的最后一个元素
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
// 将指定的元素插入list的开端
public void addFirst(E e) {
linkFirst(e);
}
// 将指定的元素增添到list的末端
public void addLast(E e) {
linkLast(e);
}
// 如果list包含指定值,则返回true
public boolean contains(Object o) {
return indexOf(o) != -1;
}
// 返回list元素的数量
public int size() {
return size;
}
// 将指定的元素增添到list的末端
public boolean add(E e) {
linkLast(e);
return true;
}
// 移除掉第一个出现在list中的指定元素
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;
}
// 将指定集合内的所有元素增添到list的尾端,按照指定集合的迭代器返回的顺序进行排序。若当该操作正在进行时对集合c进行了结构性修改,那么调用该方法后的结果是未知的。
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
// 在指定的index位置起,将指定集合内的所有元素增添到list中,将当前位于该位置的元素(如果有的话)和随后的元素向右移动(增加它们的索引)。按照指定集合的迭代器返回的顺序进行排序。
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);
if (pred == null)
first = newNode;
else
pred.next = newNode;
pred = newNode;
}
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}
// 移除掉list中所有的元素
public void clear() {
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++;
}
五 位置访问操作
// 返回list中给定索引上的元素
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
// 使用指定值替换掉list中指定索引上的元素,并返回旧元素
public E set(int index, E element) {
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}
// 将指定元素插入到list的指定索引上,并将index与其后面的元素后移
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
// 移除掉list中指定索引位置的值,并将指定索引位置其后的元素左移,并且返回被移除掉的旧值。
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
// 说明参数是否为现有元素的索引。
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
// 说明参数是迭代器或add操作的有效位置的索引。
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));
}
// 返回list指定索引上的非空结点
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;
}
}
六 查询操作
// 返回list中指定值第一次出现时的索引,如果指定值不包含在list内,则返回-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;
}
// 返回list中指定值最后一次出现时的索引,如果指定值不包含在list内,则返回-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;
}
// 队列操作
// 返回list的第一个元素,如果对象为null时返回null
public E peek() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
// 返回list的第一个元素,对象为null时抛出NoSuchElementException异常
public E element() {
return getFirst();
}
// 返回并移除list的第一个元素,如果对象为null时返回null
public E poll() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
// 返回并移除list的第一个元素,对象为null时抛出NoSuchElementException异常
public E remove() {
return removeFirst();
}
// 将指定值加到list的尾部
public boolean offer(E e) {
return add(e);
}
// 双队列操作
// 在list的前面插入指定值
public boolean offerFirst(E e) {
addFirst(e);
return true;
}
// 在list的后方插入指定值
public boolean offerLast(E e) {
addLast(e);
return true;
}
// 返回list的第一个元素,如果对象为null时返回null
public E peekFirst() {
final Node<E> f = first;
return (f == null) ? null : f.item;
}
// 返回list的最后一个元素,如果对象为null时返回null
public E peekLast() {
final Node<E> l = last;
return (l == null) ? null : l.item;
}
// 返回并移除list的第一个元素,如果对象为null时返回null
public E pollFirst() {
final Node<E> f = first;
return (f == null) ? null : unlinkFirst(f);
}
// 返回并移除list的最后一个元素,如果对象为null时返回null
public E pollLast() {
final Node<E> l = last;
return (l == null) ? null : unlinkLast(l);
}
// 在list的前面插入指定值
public void push(E e) {
addFirst(e);
}
// 返回并移除list的第一个元素,如果对象为null时抛出异常NoSuchElementException
public E pop() {
return removeFirst();
}
// 删除此list中指定元素的第一个出现项(当从头到尾遍历列表时)。如果list不包含该元素,它将保持不变。
public boolean removeFirstOccurrence(Object o) {
return remove(o);
}
// 删除此list中指定元素的最后一个出现项(当从头到尾遍历列表时)。如果list不包含该元素,它将保持不变。
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;
}
七 迭代器
// 构造一个从指向指定索引开始的迭代器
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;
}
// 移除上一次指向的结点
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++;
}
// 将上一次指向的结点的值设为e
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
// 在下一个指向结点的前面插入指定值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();
}
}
// 适配器,通过listir .previous提供递减迭代器
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();
}
}
// DescendingIterator构造器
public Iterator<E> descendingIterator() {
return new DescendingIterator();
}
八 克隆与序列化
// 直接调用Object类的clone()方法
@SuppressWarnings("unchecked")
private LinkedList<E> superClone() {
try {
return (LinkedList<E>) super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
// 返回LinkedList的浅副本。(元素本身不是克隆的。)
public Object clone() {
LinkedList<E> 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<E> x = first; x != null; x = x.next)
clone.add(x.item);
return clone;
}
// 将list装换为array
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;
}
// 将list装换为array, 并且返回的array的运行时类型为传入指定array的运行时类型
@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);
}
// spliterator.Iteratorspliterator的自定义变体
static final class LLSpliterator<E> implements Spliterator<E> {
static final int BATCH_UNIT = 1 << 10; // 批量array大小增量
static final int MAX_BATCH = 1 << 25; // 最大批量array大小
final LinkedList<E> list; // null OK unless traversed
Node<E> current; // 当前节点;空,直到初始化
int est; // 大小估计;-1直到第一次需要
int expectedModCount; // est设置时初始化
int batch; // batch size for splits
LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
this.list = list;
this.est = est;
this.expectedModCount = expectedModCount;
}
// 得到list的真实大小,并将current指向list的头结点
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;
}
// 得到long类型的list的真实大小,并将current指向list的头结点
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;
}
// 以此执行所有元素的action里面动作
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();
}
// 执行一个元素的操作,也就是action里面的操作,如果有元素则返回true,没有元素返回false。
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;
}
}
十 最后
LinkedList可以当成一个队列跟栈的组合体,大家也可以看到上面很多方法其实内部的实现是十分相似的,之所以要写这么多看似重复的方法应该是想让大家使用较为习惯的栈跟队列的操作方法。