前面只说了vector是线程安全的。下面是对其部分源码的解读。
构造函数
-
Vector(int initialCapacity, int capacityIncrement)
initialCapacity是Vector初始长度,capacityIncrement是在当前长度不够进行扩容时的扩容长度。
-
Vector(int)
只声明了初始长度,capacityIncrement是0。 -
Vector()
默认长度是10。 -
Vector(Collection )
将Collection转为Vector。
add
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
使用synchronized
进行同步,返回true。
对比另一个addElement函数,区别是没有返回值
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
扩容
和ArrayList类似的。
不过如果不指定capacityIncrement的话,扩容后是原来的2倍,而不像ArrayList的1.5倍。
2倍空间不够的话,就直接给所需要的最短长度。
最大值长度也是231-1,即Integer.MAX_VALUE。
/**
* The maximum size of array to allocate.
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
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);
}