一、底层数据结构
ObviousLy, LinkList内部使用的是一个双向链表.
二、方法思维导图
And, 继承的方法就不列了.
三、部分方法的源代码
构造方法
方法一:
public LinkedList() {
}
方法二:
public LinkedList(Collection<? extends E> c) {
this();
addAll(c);
}
进入addAll ➷
public boolean addAll(Collection<? extends E> c) {
return addAll(size, c);
}
Go on ➷
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;
}
获取指定索引处元素
public E get(int index)
这就是 LinkedList 查询元素不及 ArrayList 的原因, LinkedList得遍历链表获取引用 (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;
}
}
移除集合第一个元素
// 关键代码
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;
}
从源码可以看出LinkedList删除元素的方式比ArrayList快多了.
LinkedList只需要修改引用即可,
ArrayList则需要将该元素右边的引用都要左移.
// ArrayList删除元素
System.arraycopy(elementData, index+1, elementData, index,
numMoved);