版本:JDK 1.6 的源码
ArrayList默认初始容量 源码
The size of the ArrayList (the number of elements it contains).
数组列表的大小(包含元素的数量)。
Constructs an empty list with an initial capacity of ten.
构造一个初始容量为10的空列表。
总结 :
ArrayList内部封装了一个默认长度为10的数组。
当超出长度时,集合内部会自动生成一个新的数组。
将原数组中的元素复制到新数组中,在将新元素添加到新数组。
接下来看ArrayList扩容 源码:
/**
* Appends the specified element to the end of this list.
* 将指定的元素附加到列表的末尾。
*
*
* @param e element to be appended to this list
* 添加到此列表中的E元素
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacity(size + 1); // Increments modCount!!增量modCount
elementData[size++] = e;
return true;
}
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
* 增加<tt>ArrayList</tt>实例的容量
* 如有必要,确保它至少可以容纳元素的数量由最小容量参数指定。
* @param minCapacity the desired minimum capacity
*/