Vector的特点
底层数据结构为数组
元素排列有序、可重复
线程安全的,synchronized关键字
Vector可以指定扩容因子,扩容大小为,当增长因子大于0时,则newCapacity = oldCapacity + capacityIncrement;当增长因子不大于0时,则newCapacity = oldCapacity +oldCapacity
Vector的构造方法
// initialCapacity:初始化数组大小;capacityIncrement:增长因子
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
/**
* 增长因子默认为0
*/
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
/**
* 默认初始化大小为10
*/
public Vector() {
this(10);
}
public Vector(Collection<? extends E> c) {
elementData = c.toArray();
elementCount = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}
vector扩容机制
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
//当增长因子大于0时,则newCapacity = oldCapacity + capacityIncrement
//当增长因子不大于0时,则newCapacity = oldCapacity +oldCapacity
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);
}