和 ArrayList 一样,是通过数组实现的 List, 与 ArrayList 不同的是,Vector 是同步的。比如下面这段代码:
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++;
}
insertElementAt 这个函数是被 synchronized 修饰的,也就是说,同一个时刻,只能有一个 thread 能进入这个函数。(严格来说,同一个对象所有被 synchronized 修饰的方法,在同一个时刻都只能被一个 thread 访问,比如说在 Vector 中,add 和 set 都被 synchronized 修饰,所以 thread1 在 add 中的时候,thread2 不仅不能访问 add, 还不能访问 set)。
因为 Vector 是同步的,上锁/解锁需要开销,所以如在不需要同步的情况下,应该使用 ArrayList 代替 Vector.
另外,并不是说 Vector 是同步的,就不会抛 ConcurrentModificationException,比如:如果在创建了 Iterator 之后,Vector size 改变了,那么对 Iterator 的操作仍然会抛 ConcurrentModificationException。
总结:
1. Vector 可以看成是 ArrayList 的同步版本。
2. Vector 的操作仍然可能会抛出 ConcurrentModificationException。
参考链接:
1. https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html