Vector
类定义
@since 1.0 从JDK1.0开始提供的实现类
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
属性:
protected Object[] elementData; 内部的数据存储采用的是Object[]
protected int elementCount; 存储的元素个数
protected int capacityIncrement;容积增长的步长值
构造器
public Vector() {
this(10);
}
public Vector(int initialCapacity) { 参数为初始化容积
this(initialCapacity, 0);
}
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0) 初始化容积不能小于0
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity]; 初始化数组,不是ArrayList中的延迟初始化
this.capacityIncrement = capacityIncrement;
}
成员方法:
public synchronized boolean add(E e) { 方法上有synchronized,基本上所有的修改方法上都有synchronized关键字,所以线程安全的
modCount++; 修改次数+1
add(e, elementData, elementCount); 参数1为需要添加的元素,参数2为具体存储数据的数组,参数3为元素个数
return true;
}
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length) 如果当前存储的元素个数和数据相等则先进行扩容处理
elementData = grow();
elementData[s] = e;
elementCount = s + 1;
}
private Object[] grow() {
return grow(elementCount + 1);
}
//具体的扩容处理,调用newCapacity方法获取新容积
private Object[] grow(int minCapacity) {
return elementData = Arrays.copyOf(elementData,
newCapacity(minCapacity));
}
private int newCapacity(int minCapacity) {
int oldCapacity = elementData.length; 获取原始容积值,也就是存储数据的数组长度
//新容积值的算法:
如果设置了容积增长的步长值,则新容积为原始容积+步长值
如果没有设置容积增长的步长值,则扩容增长100%
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity <= 0) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return minCapacity;
}
return (newCapacity - MAX_ARRAY_SIZE <= 0)
? newCapacity
: hugeCapacity(minCapacity);
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;