版本:jdk1.8
底层由数组实现的
线程安全的
关键方法上都加上了synchronized同步关键字 并发安全但为此开销也会较大
已不推荐使用
Vector相关的UML
我们先来看看Vector重要属性
/**
* 对象数组
*/
protected Object[] elementData;
/**
* 数据的数量
*/
protected int elementCount;
/**
* 每次扩容的大小
*/
protected int capacityIncrement;
重要构造方法
/**
*
* @param initialCapacity 初始化数组大小
* @param 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;
}
再来看看Vector的几个方法
vector.add
/**
* 从后添加数据
*/
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
扩容到的几个方法ensureCapacityHelper,grow,hugeCapacity
/**
* 帮助扩容
*/
private void ensureCapacityHelper(int minCapacity) {
//所需的最小容量大于当前数组的长度
if (minCapacity - elementData.length > 0)
//扩容
grow(minCapacity);
}
/**
* 扩容
* @param minCapacity 所需的最小容量
*/
private void grow(int minCapacity) {
//当前数组的长度
int oldCapacity = elementData.length;
//capacityIncrement大于0就使用用户自己设置的扩容大小 newCapacity = oldCapacity + capacityIncrement
//否者 newCapacity = oldCapacity * 2
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
//扩容后的容量还是小于所需的最小容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//扩容后的容量大于最大的数组长度
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//elementData指向新数组 数据拷贝到扩容后的新数组中
elementData = Arrays.copyOf(elementData, newCapacity);
}
/**
* 超大容量的选择
* @param minCapacity 所需的最小容量
* @return
*/
private static int hugeCapacity(int minCapacity) {
//小于0直接抛出异常
if (minCapacity < 0)
throw new OutOfMemoryError();
//minCapacity大于MAX_ARRAY_SIZE就直接返回Integer.MAX_VALUE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
vector.get
/**
* 通过下标获取数据
*/
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
/**
* 通过下标获取数据
*/
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
vector.remove
/**
* 删除对应下标的数据 并返回被删除的数据
*/
public synchronized E remove(int index) {
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);
elementData[--elementCount] = null; // Let gc do its work
return oldValue;
}
总结
这里只是贴出了一些比较重要的方法,想要查看更完整的Vector源码解析点击这里