Vector源码解析
public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
//对象数组
protected Object[] elementData;
//元素数
protected int elementCount;
//容量
protected int capacityIncrement;
//同步代码块添加方法
public synchronized boolean add(E e) {
modCount++;
//保证容量
ensureCapacityHelper(elementCount + 1);
//赋值
elementData[elementCount++] = e;
return true;
}
private void ensureCapacityHelper(int minCapacity) {
//元素数大于数组长度
if (minCapacity - elementData.length > 0)
//扩容
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
//扩容原来的2倍
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
public synchronized int size() {
return elementCount;
}
}