public class Vector<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
Vector继承抽象类AbstractList,实现了List接口。
实现了RandomAccess接口,该接口为标记接口,无任何实现。
实现了Cloneable接口,可以调用Object的clone方法,返回对象的浅拷贝。
实现了java.io.Serializable接口,可以进行序列化功能。
- Vector的属性
protected Object[] elementData; //数组引用变量
protected int elementCount; //元素数量
protected int capacityIncrement; //容量增加系数
private static final long serialVersionUID = -2767605614048989439L; //序列化版本号
- Vector构造方法
public Vector(int initialCapacity, int capacityIncrement) { //能够指定数组大小和增长系统的构造方法
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity]; //创建个initialCapacity大小的数组,指向elementData引用
this.capacityIncrement = capacityIncrement;
}
public Vector(int initialCapacity) { //指定数组大小,增加系数默认为0
this(initialCapacity, 0);
}
public Vector() { //默认10大小的数组
this(10);
}
public Vector(Collection<? extends E> c) {
elementData = c.toArray(); //将Collection转换成数组指向elementData的引用
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的方法
add
public synchronized boolean add(E e) { //实现基本和ArrayList一样,增加了synchronized,来保证线程安全
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ? //这里和ArrayList有区别,假如设置过增长系统,则按增长系统来扩容
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) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
public void add(int index, E element) {
insertElementAt(element, index);
}
public synchronized void insertElementAt(E obj, int index) {
modCount++;
if (index > elementCount) {
throw new ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
}
ensureCapacityHelper(elementCount + 1);
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index] = obj;
elementCount++;
}
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
总结
其他的方法和ArrayList基本一致,就add方法里关于扩容的稍微有点区别,另外Vector很多方法都增加synchronized语句,来保证线程安全。