// 需要的容量大于数组容量的话,需要进行扩容 if (minCapacity - elementData.length > 0) grow(minCapacity); }
privatevoidgrow(int minCapacity){ // overflow-conscious code int oldCapacity = elementData.length; // 扩容1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); // 当原数组为空数组时,newCapacity为0,是小于minCapacity 10 的 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
// get public E get(int index){ rangeCheck(index);
return elementData(index); }
// indexOf publicintindexOf(Object o){ if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i; } else { for (int i = 0; i < size; i++) if (o.equals(elementData[i])) return i; } return -1; }
privateclassItrimplementsIterator<E> { // 游标 int cursor; // index of next element to return // 最后一次返回的索引位置 int lastRet = -1; // index of last element returned; -1 if no such // 当Itr被实例化的时候,记录一下迭代器被实例化时ArrayList的修改次数(在用ArrayList进行add/remove操作时modCount每次都加一) int expectedModCount = modCount;
Itr() {}
publicbooleanhasNext(){ return cursor != size; }
@SuppressWarnings("unchecked") 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]; }
publicvoidremove(){ if (lastRet < 0) thrownew IllegalStateException(); // 检查是否被修改了 checkForComodification();
@Override @SuppressWarnings("unchecked") publicvoidforEachRemaining(Consumer<? super E> consumer){ Objects.requireNonNull(consumer); finalint size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { thrownew ConcurrentModificationException(); } 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(); }