首次向列表中添加元素时,容量将设置为10。
看到这个:
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
完整程序
步骤1:
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
步骤2:
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}
步骤3,列表
grows
:
private Object[] grow() {
return grow(size + 1); // size is 0 here
}
private Object[] grow(int minCapacity) {
return elementData = Arrays.copyOf(elementData,
newCapacity(minCapacity)); // newCapacity(1) will return 10, see step 4, the elementData will have capacity 10.
}
步骤4,调用
newCapacity(1)
:
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity <= 0) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
return Math.max(DEFAULT_CAPACITY, minCapacity); // will return 10 here !!!!
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return minCapacity;
}
return (newCapacity - MAX_ARRAY_SIZE <= 0)
? newCapacity
: hugeCapacity(minCapacity);
}