publicbooleanremove(Object o){ if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { // 删除第一个equals成立的元素 fastRemove(index); returntrue; } } returnfalse; }
privatevoidfastRemove(int index){ modCount++; int numMoved = size - index - 1; // 计算index之后实际有多少元素 if (numMoved > 0) // 将index之后的元素整体向前移到一位,然后删除末尾元素 System.arraycopy(elementData, index+1, elementData, index, numMoved);
privateclassItrimplementsIterator<E> { int cursor; // 下一次返回元素的索引 int lastRet = -1; // 当前返回的元素的索引 int expectedModCount = modCount; // 开始迭代时,list的修改次数
publicbooleanhasNext(){ return cursor != size; }
// 返回cursor所在位置的元素,并记lastRet = cursor,cursor = cursor + 1 public E next(){ checkForComodification(); int i = cursor; if (i >= size) thrownew NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownew ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
// 删除当前元素,然后修正cursor为当前位置(因为当前位置上实际上已经是原先的下一位元素) publicvoidremove(){ if (lastRet < 0) thrownew IllegalStateException(); checkForComodification();
publicvoidadd(int index, E element){ checkPositionIndex(index); if (index == size) linkLast(element); else linkBefore(element, node(index)); }
voidlinkLast(E e){ final Node<E> l = last; final Node<E> newNode = new Node<>(l, e, null); // 创建newNode,并将其prev记为原先的last last = newNode; //将newNode记为新的last if (l == null) first = newNode; // 如果原先是空链表,那么将first也记为newNode else l.next = newNode; // 将原先last的next记为newNode size++; modCount++; }
Node<E> node(int index){ if (index < (size >> 1)) { // 确定是从first还是从last遍历位置 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; } }
voidlinkBefore(E e, Node<E> succ){ final Node<E> pred = succ.prev; // 记原index位置的节点为succ,它的前一个节点记为pred final Node<E> newNode = new Node<>(pred, e, succ); // 创建newNode,并将其prev记为pred,next记为succ succ.prev = newNode; // 将succ的prev记为newNode if (pred == null) first = newNode; // 如果原先succ就是头节点first,那么直接将newNode记为first else pred.next = newNode; // 将pred的next指向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; }
E unlink(Node<E> x){ final E element = x.item; // 记要删除的节点为element,前后节点分别为prev和next final Node<E> next = x.next; final Node<E> prev = x.prev;