List集合
ArrayList
创建数组的时候 长度是0
第一次添加元素的时候 初始化数组的长度10
下面是有关ArrayList容量的源码
private static final int DEFAULT_CAPACITY = 10;//默认容量10
private static final Object[] EMPTY_ELEMENTDATA = {
};
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {
};//默认空数组
transient Object[] elementData;
private int size;//默认为0
public ArrayList() {
//无参构造方法,Object数组长度为0
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
private void ensureCapacityInternal(int minCapacity) {
//此方法目的是在没有指定集合容量时,第一次add时给集合分配10的默认空间
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
public ArrayList(int initialCapacity) {
//有参构造方法,Object数组长度为initialCapacity
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//数组集合最大长度2^31-1-8
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(