- 使用默认的进行
源码解析
List<Integer> list=new ArrayList<Integer>();
// 默认是创建10个长度的
private static final int DEFAULT_CAPACITY = 10;
// 创建的 加上数字
public ArrayList(int 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 void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 扩大1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0) // 比数值小就赋值为数值
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0) // 大于MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; 就赋值为整形的max_value 或者原值
newCapacity = hugeCapacity(minCapacity);
// return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE : MAX_ARRAY_SIZE;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
发表回复