/** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */ public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; }
size : ArrayList的大小(包含的元素个数)
ensureCapacityInternal(int minCapacity) 方法确保数组容器内部正确 :
private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); }
DEFAULTCAPACITY_EMPTY_ELEMENTDATA为构造ArrayList时的的初始化数组
DEFAULT_CAPACITY=10
minCapacity取10和size+1的最大值
ensureExplicitCapacity(int minCapacity)确保明确容量 :
private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); }
modCount继承自AbstractList,记录了list在结构上变更的次数.所谓结构变更就是改变List的大小或是因为进程中的迭代导致了错误结果而打乱其顺序.
if判断保证不会溢出
grow(int minCapacity)
/** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); 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); }
若扩充过后的容量小于最少需要的容量,扩充=最少
MAX_ARRAY_SIZE=Integer.MAX_VALUE - 8;//数组能分配的最大值,超出则抛出OutOfMemoryError
如果扩充后的容量大于MAX_ARRAY_SIZE,则返回hugeCapacity(minCapacity);
private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; }
大容量下,超出int上限返回Integer上限,否则返回Integer上限-8
Arrays.copyOf(elementData, newCapacity)
最后调用
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
使用本地接口,在C/C++里完成数组复制扩充
原文:http://my.oschina.net/sherlocked/blog/375465