privatevoidgrow(int minCapacity){// overflow-conscious codeint oldCapacity = elementData.length;// 扩容旧容量的一半int newCapacity = oldCapacity +(oldCapacity >>1);// 如果仍然不够,则取需要的容量大小if(newCapacity - minCapacity <0)
newCapacity = minCapacity;// 最小容量大于Integer.MAX_VALUE - 8;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);}
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])){fastRemove(index);returntrue;}}returnfalse;}
fastRemove
privatevoidfastRemove(int index){
modCount++;int numMoved = size - index -1;if(numMoved >0)System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size]=null;// clear to let GC do its work}
遍历
Iterator
privateclassItrimplementsIterator<E>{int cursor;// index of next element to returnint lastRet =-1;// index of last element returned; -1 if no suchint expectedModCount = modCount;publicbooleanhasNext(){return cursor != size;}@SuppressWarnings("unchecked")publicEnext(){checkForComodification();int i = cursor;if(i >= size)thrownewNoSuchElementException();Object[] elementData =ArrayList.this.elementData;if(i >= elementData.length)thrownewConcurrentModificationException();
cursor = i +1;return(E) elementData[lastRet = i];}......finalvoidcheckForComodification(){if(modCount != expectedModCount)thrownewConcurrentModificationException();}}