Vector 实现了List接口,它的底层是一个数组,和ArrayList很相似,最大的不同点在于线程安全,这个类的对底层数组进行变动的public方法(除去构造)都是同步方法。
构造方法
1. 无参构造
public Vector() {
this(10);
}
这里的所谓无参构造,只是隐式的调用带参构造
2. 带参构造
public Vector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
public Vector(Collection<? extends E> c) {
elementData = c.toArray();
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(int initialCapacity, int capacityIncrement):第一个参数指定底层数组大小,第二个参数指定每次扩容的大小。
Vector(int initialCapacity):相当于调用Vector(initialCapacity, 0)。
Vector(Collection < ? extends E > c):将collection的子类直接转换成Vector类。
常用方法
1. add(E e)
public synchronized boolean add(E e) {
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) ?
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;
}
其实Vector和ArrayList真的很相似,因为底层是数组,所以直接插入元素的话,可能会造成数组越界之类的问题,所以在每次插入前都会检验底层数组的大小是否足够,如果不够的话还会进行一次扩容,具体的扩容系数可以在构造函数里面指定,不指定的话有按照当前数组大小来扩展。
2. remove(int index)
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;
}
这个remove方法也和ArrayList很类似,首先考虑index的合法性,其实讲index后面的元素全部前移一位,然后最后一个置空,elementCount减一,这个会和ArrayList不太一样,ArrayList会有一个size的属性,这个并没有,它只有一个size()方法,返回的是elementCount。
3. indexOf(Object o)
public int indexOf(Object o) {
return indexOf(o, 0);
}
public synchronized int indexOf(Object o, int index) {
if (o == null) {
for (int i = index ; i < elementCount ; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = index ; i < elementCount ; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
和ArrayList一样,直接返回对应的元素内容,只不过和我之前说的一样是线程安全的一个方法。