天天看點

Vector源碼分析

//初始化為10

protected Object[] elementData;

//大小

protected int elementCount;

//預設是0,可通過構造器傳入

protected int capacityIncrement;

public Vector() {

this(10);

}

public synchronized boolean add(E e) {

modCount++;

ensureCapacityHelper(elementCount + 1);

elementData[elementCount++] = e;

return true;

//擴容

private void grow(int minCapacity) {

// overflow-conscious code

int oldCapacity = elementData.length;

//擴容方式 舊容量+舊容量|capacityIncrement(capacityIncrement預設為0,可以通過構造器傳入)

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);

//巧妙的删除

public synchronized E remove(int index) {

if (index >= elementCount)

throw new ArrayIndexOutOfBoundsException(index);

E oldValue = elementData(index);

繼續閱讀