public boolean add(E e) {
linkLast(e);
return true;
}
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++;
}
public void add(int index, E element) {
checkPositionIndex(index);
if (index == size)
linkLast(element);
else
linkBefore(element, node(index));
}
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指向新节点
succ.prev = newNode;
// 判断尾节点是否为空,为空表示当前链表没有节点
if (pred == null)
first = newNode;
else
pred.next = newNode; // succ节点前驱的后继引用指向新节点
size++;
modCount++;
}
LinkedList新增元素的逻辑流程
(1)创建新节点,并指明新节点的前驱和后继
(2)将succ的前驱引用指向新节点
(3)如果succ的前驱不为空,则将succ前驱的后继引用指向新节点
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;
}
// 上面先将前驱与新节点连接 接下来 最后一个新节点连接后继节点(succ节点 或 last节点)
if (succ == null) {
last = pred;
} else {
pred.next = succ;
succ.prev = pred;
}
size += numNew;
modCount++;
return true;
}