/** * 删除此列表中指定位置的元素。将所有后续元素向左移动(从其索引中减去一个)。 * * @param index 要删除的元素的索引 * @return 从列表中删除的元素 * @throws IndexOutOfBoundsException */ public E remove(int index) { rangeCheck(index);
modCount++; EoldValue= elementData(index);
intnumMoved= size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work
/** * 从此列表中删除第一次出现的指定元素,如果不存在该元素就不改变列表. * * @param o 要从此列表中删除的元素 * @return 如果列表里有该元素则返回 true */ publicbooleanremove(Object o) { if (o == null) { for (intindex=0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { for (intindex=0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }
privatevoidfastRemove(int index) { modCount++; intnumMoved= size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
publicintindexOf(Object o) { if (o == null) { for (inti=0; i < size; i++) if (elementData[i]==null) return i; } else { for (inti=0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; }
privateclassItrimplementsIterator<E> { int cursor; // index of next element to return intlastRet= -1; // index of last element returned; -1 if no such intexpectedModCount= modCount;
Itr() {}
publicbooleanhasNext() { return cursor != size; }
@SuppressWarnings("unchecked") public E next() { checkForComodification(); inti= cursor; if (i >= size) thrownewNoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownewConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
publicvoidremove() { if (lastRet < 0) thrownewIllegalStateException(); checkForComodification();
@Override @SuppressWarnings("unchecked") publicvoidforEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); finalintsize= ArrayList.this.size; inti= cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { thrownewConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); }
finalvoidcheckForComodification() { if (modCount != expectedModCount) thrownewConcurrentModificationException(); } }