因为其方法全是线程安全的,被淘汰了,在方法声明上加synchronized,而并不是所有的场景都要用线程安全。这一点和HashTable类被淘汰的原因一样。
一、构造方法
底层数组长度默认初始化为10
protected Object[] elementData;
protected int elementCount;
public Vector() {
this(10);
}
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
二、add方法
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
pri
vate void ensureCapacityHelper(int minCapacity) {
// 如果超出当前数组长度就扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
三、扩容机制
底层扩容数组长度为 2 倍
/**
* 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.
* 要分配的数组的最大大小。一些 VM 在数组中保留一些标题字。
* 尝试分配更大的数组可能会导致 OutOfMemoryError:请求的数组大小超过 VM 限制
*/
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);
}
四、ArrayList实现类和Vector类的区别
相同点:
- 底层都是数组的扩容,
- 数组特点:查询快,增删慢,数据可重复。
不同点:
- ArrayList底层扩容长度为原数组的 1.5 倍,线程不安全,效率高。
- Vector底层扩容长度为原数组的 2 倍 ,线程安全,效率低。