源自:jdk1.8.0_121 LinkedList继承自AbstractSequentialList,实现了List、Deque、Cloneable、Serializable。
LinkedList内部是一个双向链表
变量
transient int size = 0;
// 链表的第一个结点
transient Node first;
// 链表的最后一个结点
transient Node last;
构造方法
public LinkedList() {
}
public LinkedList(Collection extends E> c) {
this();
addAll(c);
}
LinkedList$Node
Node是LinkedList的内部类,所有增加、修改结点的操作都是通过Node对象
private static class Node {
// 存放的数据
E item;
// 下一个结点
Node next;
// 上一个结点
Node prev;
Node(Node prev, E element, Node next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
add方法
public boolean add(E e) {
// 在链表的最后增加一个结点
linkLast(e);
return true;
}
void linkLast(E e) {
// 保存当前状态最后一个结点
final Node l = last;
// 新增一个结点
final Node newNode = new Node<>(l, e, null);
// 将当前状态最后一个结点重新赋值
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
remove方法
remove有两个重载方法,分别是remove(int index)和remove(Object o)
// 删除索引对应的结点
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
// 删除一个值(重复的也只会删除其中一个)
public boolean remove(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;
}
E unlink(Node x) {
// assert x != null;
final E element = x.item;
final Node next = x.next;
final Node prev = x.prev;
// 将x与x.prev从链表中断开
if (prev == null) {
first = next;
} else {
// 将x.prev.next = x 变为 x.prev.next = x.next
prev.next = next;
x.prev = null;
}
// 将x与x.next从链表中断开
if (next == null) {
last = prev;
} else {
// 将x.next.prev = x 变为 x.next.prev = x.prev
next.prev = prev;
x.next = null;
}
x.item = null;
// 实际数量-1
size--;
// 操作次数+1
modCount++;
// 返回删除的结点值
return element;
}
Node node(int index) {
// assert isElementIndex(index);
// 如果索引小于实际大小的一半,就从索引的左边遍历,反之。
if (index < (size >> 1)) {
Node x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
由于LinkedList的node方法是通过索引逐一遍历,因此查找的效率会比ArrayList直接在数组中找到索引对应的值慢的多。