privatevoidlinkFirst(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++; }
publicbooleanremove(Object o){ //分为两种情况,分别进行迭代处理 if (o == null) { for (Node<E> x = first; x != null; x = x.next) { if (x.item == null) { unlink(x); returntrue; } } } else { for (Node<E> x = first; x != null; x = x.next) { if (o.equals(x.item)) { unlink(x); returntrue; } } } returnfalse; }
Object[] a = c.toArray(); int numNew = a.length; if (numNew == 0) returnfalse; //c为空,直接返回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++; returntrue; }
Node<E> node(int index){ // assert isElementIndex(index); //这里有个细节,由于LinkedList是双向链表,所以可以从两边开始遍历,先判断索引在前半部分还是后半部分 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; } }