概述
Vector是一个以动态数组(支持扩展)实现的List(线程安全)
UML类图
Vector实现了List接口,提供了增删改查的基础操作;
Vector实现了Serializable接口,可以被序列化;
Vector实现了Cloneable接口,可以被克隆;
Vector实现了RandomAccess接口,支持随机访问;
源码解析
属性
/** 数组 */
protected Object[] elementData;
/** 数组个数 */
protected int elementCount;
/** 自增量 */
protected int capacityIncrement;
构造器
//默认初始化数组容量10
public Vector() {
this(10);
}
public Vector(Collection<? extends E> c) {
elementData = c.toArray();
elementCount = elementData.length;
// 由于子类可以重写Collection的toArray接口,所以返回类型不一定是Object[]类型,需要加判断
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
方法
add(E e)
功能
添加元素到数组末尾(synchronized修饰方法,线程安全),平均时间复杂度O(1);
流程
- 检查是否需要扩容;
- 判断本次的最小容量与数组容量大小,大于转步骤3,小于转步骤5;
- 新容量默认扩大为旧容量+自增量(自增量为0,则自增量值默认为当前旧容量),如果还小于本次的最小容量,则新容量=本次的最小容量;如果新容量大于最大数组容量,调用hugeCapacity(int minCapacity)赋值最大容量;
- 复制旧数据到新数组;
- 将元素添加至数组末尾;
源码
public synchronized boolean add(E e) {
//fail-fast机制
modCount++;
//扩容判断
ensureCapacityHelper(elementCount + 1);
//赋值
elementData[elementCount++] = e;
return true;
}
private void ensureCapacityHelper(int minCapacity) {
// 当前长度>数组长度,扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
//如果自增量>0,每次新增自增量,否则每次新增1倍容量
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);
}
get(int index)
功能
根据指定下标返回数据(synchronized修饰方法,线程安全),平均时间复杂度O(1);
流程
-
检查数组是否越界
-
返回指定下标的数据
源码
public synchronized E get(int index) {
//数组越界判断
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
//返回值
return elementData(index);
}
remove(int index)
功能
功能:删除并返回指定下标的数据(synchronized修饰方法,线程安全),平均时间复杂度为O(n)
流程
- 检查数组越界
- 获取指定下标元素
- 将index+1处开始的numMoved个元素,移动到index处
- 清除最后一位元素
- 返回值
源码
public synchronized E remove(int index) {
//fail-fast机制
modCount++;
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
E oldValue = elementData(index);
int numMoved = elementCount - index - 1;
//待删除元素不在末尾的话,元素向前移动一位
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//清空idnex下标元素
elementData[--elementCount] = null;
return oldValue;
}
总结
Vector使用数组存储元素,当数组长度不够时扩容,默认为旧容量+自增量(自增量为0则自增量值默认为当前旧容量),扩容后不可压缩
Vector支持随机访问,通过下标访问速度极快,平均时间复杂度O(1)
Vector添加数据到尾部速度极快,平均时间复杂度O(1)
Vector添加数据到指定位置速度较慢,需要移动元素,平均时间复杂度O(n)
Vector删除尾部数据速度极快,平均时间复杂度O(1)
Vector删除指定位置数据速度较慢,需要移动元素,平均时间复杂度O(n)