目录
基本介绍
Vector和ArrayList类似,底层都是由Object数组实现的,可以使用索引实现随机访问,同时它也是线程安全的
常用方法
Vector(int initialCapacity, int capacityIncrement)
Vector(int initialCapacity)
Vector()
Vector(Collection<? extends E> c)
synchronized int size()
synchronized boolean isEmpty()
boolean contains(Object o)
synchronized boolean containsAll(Collection<?> c)
synchronized int indexOf(Object o, int index)
synchronized int lastIndexOf(Object o)
synchronized int lastIndexOf(Object o, int index)
synchronized E get(int index)
synchronized boolean add(E e)
void add(int index, E element)
boolean remove(Object o)
synchronized E remove(int index)
synchronized boolean addAll(Collection<? extends E> c)
synchronized boolean addAll(int index, Collection<? extends E> c)
synchronized boolean removeAll(Collection<?> c)
源码解析
1. 变量
// 底层数组
protected Object[] elementData;
// Vector中有效元素个数
protected int elementCount;
// 扩容因子
protected int capacityIncrement;
// 修改次数
protected transient int modCount
// 集合的最大容量,即2的31次方 -1 -8
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
2. 构造函数
// vector的构造函数
public Vector(int initialCapacity, int capacityIncrement) {
super();
// 如果初始化容量小于0,则抛异常
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
this.elementData = new Object[initialCapacity];
// 给扩容因子赋值,后面在数组扩容时使用
this.capacityIncrement = capacityIncrement;
}
// vector的构造函数
public Vector(int initialCapacity) {
// 此处调用了上面的构造方法,可以看到,如果扩容因子没有值,则默认0
this(initialCapacity, 0);
}
3. add(E e)
// 像集合中添加元素,加了synchronized同步锁,保证线程安全
public synchronized boolean add(E e) {
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) {
// 获取当前容量,就是数组的长度
int oldCapacity = elementData.length;
// 计算新容量,此处用到了扩容因子capacityIncrement,扩容因子的来源请看上面的构造方法解析
// 如果扩容因子大于0,则根据扩容因子进行扩容(当前容量+扩容因子)
// 如果扩容因子不大于0,则默认扩容当前的一倍
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0)
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
}
Vector的方法其实跟ArrayList差不多,所以就不做过多的解析了,最重要的一点其实就是相比于ArrayList它在许多需要操作数组的方法上都增加了synchronized同步锁来保证线程安全
总结
1. Vector底层是基于数组实现的
2. Vector是线程安全的
3. Vector支持索引的随机访问
4. 在扩容因子为0的情况下,Vector每次扩容为当前的一倍