Vector介绍
构造器
public Vector() // 实际上调用了Vector(10)
public Vector(int initialCapacity) // 实际上调用了Vector(initialCapacity,0)
public Vector(int initialCapacity, int capacityIncrement)
public Vector(Collection<? extends E> c)
扩容原则:
是否设置容量扩展值capacityIncrement,如果设置了,currentCapcity = oldCapacity + capacityIncrement
如果没设置容量扩展值,则currentCapcity =oldCapacity + oldCapacity(即扩容增加一倍)。
但是如果扩容了一次后,发现currentCapcity< minCapacity,最终使用currentCapcity = currentCapcity
源码:
java.util.Vector
/**
* Increases the capacity of this vector, if necessary, to ensure
* that it can hold at least the number of components specified by
* the minimum capacity argument.
*
* <p>If the current capacity of this vector is less than
* {@code minCapacity}, then its capacity is increased by replacing its
* internal data array, kept in the field {@code elementData}, with a
* larger one. The size of the new data array will be the old size plus
* {@code capacityIncrement}, unless the value of
* {@code capacityIncrement} is less than or equal to zero, in which case
* the new capacity will be twice the old capacity; but if this new size
* is still smaller than {@code minCapacity}, then the new capacity will
* be {@code minCapacity}.
*
* @param minCapacity the desired minimum capacity
*/
public synchronized void ensureCapacity(int minCapacity) {
if (minCapacity > 0) {
modCount++;
ensureCapacityHelper(minCapacity);
}
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
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);
}
ArrayList
构造器
public ArrayList()
public ArrayList(Collection <? extends E> c)
public ArrayList(int initialCapacity)
扩容原则:
扩容增加0.5倍,currentCapcity = oldCapacity + 0.5 * oldCapacity
如果扩容后 currentCapcity < minCapacity,则currentCapcity = minCapacity
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
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(elementData, newCapacity);
}