上一篇咱们分析了ArrayList这个用数组实现的List集合类,今天继续来分析一个跟它比较类似的List集合类——LinkedList,不过LinkedList的底层实现是链表,它们内部的实现仍是有很大差别的。java
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable复制代码
能够看到对比起 ArrayList,LinkedList并无实现RandomAccess 接口,因此咱们能够知道它并不支持随机访问。 接下来咱们看看LinkedList的具体实现node
每一个链表存储了 first 和 last 指针分别指向头节点和尾节点:
数组
//总节点数
transient int size = 0;
//头节点
transient Node<E> first;
//尾节点
transient Node<E> last;
复制代码
能够发现LinkedList是基于双向链表实现的,使用 Node 存储链表节点信息。
安全
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 void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}复制代码
//尾插到尾节点并将新节点设为尾节点
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++;
}
复制代码
public E set(int index, E element) {
// 检查index是否合法
checkElementIndex(index);
Node<E> x = node(index);
E oldVal = x.item;
x.item = element;
return oldVal;
}复制代码
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 void add(E e) {
checkForComodification();
lastReturned = null;
if (next == null)
linkLast(e);
else
linkBefore(e, next);
nextIndex++;
expectedModCount++;
}
public void set(E e) {
if (lastReturned == null)
throw new IllegalStateException();
checkForComodification();
lastReturned.item = e;
}
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++;
}
// fail-fast机制
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}复制代码
ArrayList的具体分析能够看一下个人上一篇文章:juejin.im/post/5d29d6…dom