Collection家族成员关系图
说明:在上图中可以看到,Vector和ArrayList在继承关系中是平辈关系,可以简单的理解Vector就是线程安全的ArrayList
基本介绍
- Vector实现了一个
动态数组,主要用在无法确认长度或可以改变长度的数组 - Vector是
矢量队列。它是jdk1.0版本添加的类 继承AbstractList、实现List,RandomAccess,Cloneable,java.io.Serializable这些接口,由于它是同步的,则支持并发访问,也因此速度较慢,后来在ArrayList和LinkedList等出现后,它的使用则越来越少 - 继承
AbstractList,实现了List;所以,它是一个队列,支持相关的添加、删除、修改、遍历等功能 - Vector 实现了
RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在Vector中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。 - Vector 实现了
Cloneable接口,即实现clone()函数。它能被克隆。 - Vector 方法加上了synchronized关键字,则线程安全的,但也导致了性能要低于ArrayList

Vector源码解析
代码
import java.util.Vector;@SuppressWarnings({"all"})public class VectorTeat {public static void main(String[] args) {//无参构造Vector vector = new Vector();for (int i = 0; i < 10; i++) {vector.add(i);}vector.add(100);System.out.println(vector);}}

package java.util;import java.io.IOException;import java.io.ObjectInputStream;import java.io.StreamCorruptedException;import java.util.function.Consumer;import java.util.function.Predicate;import java.util.function.UnaryOperator;public class Vector<E>extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable{//这就是存储数据的数组,注意啦这是一个动态的数组protected Object[] elementData;//当前元素的个数protected int elementCount;//容量增长系数,扩容时使用protected int capacityIncrement;// Vector的序列版本号private static final long serialVersionUID = -2767605614048989439L;//指定数组的初始化大小,和增长系数。容量不能小于0public Vector(int initialCapacity, int capacityIncrement) {super();if (initialCapacity < 0)throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);this.elementData = new Object[initialCapacity];this.capacityIncrement = capacityIncrement;}//指定容量,增长系数为 0public Vector(int initialCapacity) {this(initialCapacity, 0);}//采用默认 容量 10 增长系数为 0public Vector() {this(10);}//使用另一个集合构造改集合public Vector(Collection<? extends E> c) {elementData = c.toArray();elementCount = elementData.length;// c.toArray可能(错误地)不返回Object []if (elementData.getClass() != Object[].class)elementData = Arrays.copyOf(elementData, elementCount, Object[].class);}//这时将Veector中的所有数据都拷贝到anArray中去public synchronized void copyInto(Object[] anArray) {System.arraycopy(elementData, 0, anArray, 0, elementCount);}//缩小当前数组的容量,为当前数组中元素的个数public synchronized void trimToSize() {modCount++;int oldCapacity = elementData.length;if (elementCount < oldCapacity) {//使用Arrays.copyOf方法将数据中的元素copy到新数组中elementData = Arrays.copyOf(elementData, elementCount);}}//如有必要,增加当前数组的容量,以确保至少可以保存minCapacity容量参数指定的元素个数public synchronized void ensureCapacity(int minCapacity) {if (minCapacity > 0) {modCount++;ensureCapacityHelper(minCapacity);}}/*** 和上面方法的功能一样,这么做的原因是这是一个内部使用的方法,使用就没有必要去同步,这样的好处就是可用* 降低同步所带来的开销*/private void ensureCapacityHelper(int minCapacity) {if (minCapacity - elementData.length > 0)grow(minCapacity);}//当前数组的最大容量,其实扩容可用扩容到 Integer.MAX_VALUE往下面看就知道了private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;//Vectory的扩容方法,嗯嗯看看它的扩容机制吧private void grow(int minCapacity) {int oldCapacity = elementData.length;//新的数组长度 = 旧数组长度 + 增长系数大于0加增长系数 否则 + 旧数组长度int newCapacity = oldCapacity + ((capacityIncrement > 0) ?capacityIncrement : oldCapacity);//如果计算后还不够就 = 最小扩容数if (newCapacity - minCapacity < 0)newCapacity = minCapacity;//如果大于最大扩容数if (newCapacity - MAX_ARRAY_SIZE > 0)/*** hugeCapacity 返回 嗯嗯从这我们可用看错最大看扩容量位Integer.MAX_VALUE* (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE : MAX_ARRAY_SIZE;**/newCapacity = hugeCapacity(minCapacity);elementData = Arrays.copyOf(elementData, newCapacity);}private static int hugeCapacity(int minCapacity) {if (minCapacity < 0) // overflowthrow new OutOfMemoryError();return (minCapacity > MAX_ARRAY_SIZE) ?Integer.MAX_VALUE :MAX_ARRAY_SIZE;}//设置当前数组的元素个数,如果小于当前元素的个数//那么就将多出来的元素置空,如果大于数组扩容public synchronized void setSize(int newSize) {modCount++;if (newSize > elementCount) {ensureCapacityHelper(newSize);} else {for (int i = newSize ; i < elementCount ; i++) {elementData[i] = null;}}elementCount = newSize;}//当前数组的大小public synchronized int capacity() {return elementData.length;}//元素个数public synchronized int size() {return elementCount;}//是否为空public synchronized boolean isEmpty() {return elementCount == 0;}//返回“Vector中全部元素对应的Enumeration(枚举)public Enumeration<E> elements() {//通过匿名类实现 Enumeration 接口return new Enumeration<E>() {int count = 0;public boolean hasMoreElements() {return count < elementCount;}public E nextElement() {synchronized (Vector.this) {if (count < elementCount) {return elementData(count++);}}throw new NoSuchElementException("Vector Enumeration");}};}//是否包含指定元素public boolean contains(Object o) {//从顶一位开始查找 通过 >= 0 判断是否包含return indexOf(o, 0) >= 0;}//返回指定元素在数组中的位置public int indexOf(Object o) {return indexOf(o, 0);}//指定元素 开始位置 返回改元素在数组中的下标public synchronized int indexOf(Object o, int index) {//判断以下是否位空,为空 用 == 不位空用 equalsif (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;}//如果每找到返回状态码 -1return -1;}//重后往前找,元素在数组中的位置。重最后一个元素开始找起public synchronized int lastIndexOf(Object o) {return lastIndexOf(o, elementCount-1);}//指定查找元素和查找起始位置。从后往前找public synchronized int lastIndexOf(Object o, int index) {if (index >= elementCount)throw new IndexOutOfBoundsException(index + " >= "+ elementCount);if (o == null) {//就是倒着循环判断for (int i = index; i >= 0; i--)if (elementData[i]==null)return i;} else {for (int i = index; i >= 0; i--)if (o.equals(elementData[i]))return i;}//找不到一样返回状态码 -1return -1;}//返回指定下标处的元素public synchronized E elementAt(int index) {if (index >= elementCount) {throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);}return elementData(index);}//返回第一个元素public synchronized E firstElement() {if (elementCount == 0) {throw new NoSuchElementException();}return elementData(0);}//返回最后一个元素public synchronized E lastElement() {if (elementCount == 0) {throw new NoSuchElementException();}return elementData(elementCount - 1);}//修改指定位置的元素public synchronized void setElementAt(E obj, int index) {if (index >= elementCount) {throw new ArrayIndexOutOfBoundsException(index + " >= " +elementCount);}elementData[index] = obj;}//移除指定位置的元素public synchronized void removeElementAt(int index) {modCount++;if (index >= elementCount) {throw new ArrayIndexOutOfBoundsException(index + " >= " +elementCount);}else if (index < 0) {throw new ArrayIndexOutOfBoundsException(index);}//j 是删除元素在数组中的位置int j = elementCount - index - 1;if (j > 0) {//移动数组位置:新数组位置 = 原数组移除元素的后一位都通过copy向前移动一位System.arraycopy(elementData, index + 1, elementData, index, j);}elementCount--;//copy会多出来一位,设置位null 让gc做它的工作elementData[elementCount] = null; /* to let gc do its work */}//指定位置插入元素public synchronized void insertElementAt(E obj, int index) {modCount++;if (index > elementCount) {throw new ArrayIndexOutOfBoundsException(index+ " > " + elementCount);}//是否需要扩容ensureCapacityHelper(elementCount + 1);//通过arraycopy方法在插入位置向后移动以为,方便元素插入System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);elementData[index] = obj;elementCount++;}//添加元public synchronized void addElement(E obj) {modCount++;ensureCapacityHelper(elementCount + 1);elementData[elementCount++] = obj;}//移除元素public synchronized boolean removeElement(Object obj) {modCount++;//通过 indexOf获取在数组中的位置int i = indexOf(obj);if (i >= 0) {removeElementAt(i);return true;}return false;}//删除当前数组中的所有元素public synchronized void removeAllElements() {modCount++;//让gc做它的工作for (int i = 0; i < elementCount; i++)elementData[i] = null;elementCount = 0;}//克隆函数public synchronized Object clone() {try {@SuppressWarnings("unchecked")Vector<E> v = (Vector<E>) super.clone();//将当前Vector的全部元素拷贝到v中v.elementData = Arrays.copyOf(elementData, elementCount);v.modCount = 0;return v;} catch (CloneNotSupportedException e) {// this shouldn't happen, since we are Cloneablethrow new InternalError(e);}}//返回存有当前集合所有元素引用的数组public synchronized Object[] toArray() {return Arrays.copyOf(elementData, elementCount);}// 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型@SuppressWarnings("unchecked")public synchronized <T> T[] toArray(T[] a) {//如果a的大小小于当前元素的个数 那么就建立新的数组返回//如果a的大小大于或等于当前元素的大小就将元素copy到a数组中去if (a.length < elementCount)return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());System.arraycopy(elementData, 0, a, 0, elementCount);if (a.length > elementCount)a[elementCount] = null;return a;}//返回指定位置的元素 这个是内部使用 不加锁,但加锁的那个方法//也是调用此方法。看下面的get方法就指定了@SuppressWarnings("unchecked")E elementData(int index) {return (E) elementData[index];}//加锁了public synchronized E get(int index) {if (index >= elementCount)throw new ArrayIndexOutOfBoundsException(index);return elementData(index);}//修改指定位置的元素public synchronized E set(int index, E element) {if (index >= elementCount)throw new ArrayIndexOutOfBoundsException(index);E oldValue = elementData(index);elementData[index] = element;return oldValue;}//添加元素public synchronized boolean add(E e) {modCount++;ensureCapacityHelper(elementCount + 1);elementData[elementCount++] = e;return true;}//移除匹配元素public boolean remove(Object o) {return removeElement(o);}//指定位置添加元素public void add(int index, E element) {insertElementAt(element, 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 workreturn oldValue;}//清空集合当前的所有数据public void clear() {removeAllElements();}//如果此Vector包含指定Collection中的所有元素,则返回truepublic synchronized boolean containsAll(Collection<?> c) {return super.containsAll(c);}//将指定集合的所有数据都添加进当前集合public synchronized boolean addAll(Collection<? extends E> c) {modCount++;Object[] a = c.toArray();int numNew = a.length;ensureCapacityHelper(elementCount + numNew);System.arraycopy(a, 0, elementData, elementCount, numNew);elementCount += numNew;return numNew != 0;}//当前Vectory中包含指定集合中的元素通通移除掉public synchronized boolean removeAll(Collection<?> c) {return super.removeAll(c);}//删除“非集合c中的元素”public synchronized boolean retainAll(Collection<?> c) {return super.retainAll(c);}// 从index位置开始,将集合c中所有元素添加到Vector中public synchronized boolean addAll(int index, Collection<? extends E> c) {modCount++;if (index < 0 || index > elementCount)throw new ArrayIndexOutOfBoundsException(index);Object[] a = c.toArray();int numNew = a.length;ensureCapacityHelper(elementCount + numNew);int numMoved = elementCount - index;if (numMoved > 0)System.arraycopy(elementData, index, elementData, index + numNew,numMoved);System.arraycopy(a, 0, elementData, index, numNew);elementCount += numNew;return numNew != 0;}//Vector的equals实现,就是调用父类AbstractList的equals方法public synchronized boolean equals(Object o) {return super.equals(o);}//hashCode码public synchronized int hashCode() {return super.hashCode();}//将当前对象转换位字符串public synchronized String toString() {return super.toString();}//获取Vector中fromIndex(包括)到toIndex(不包括)的子集public synchronized List<E> subList(int fromIndex, int toIndex) {return Collections.synchronizedList(super.subList(fromIndex, toIndex),this);}//移除Vectory中 fromIndex 到 toIndex位置上的所有元素protected synchronized void removeRange(int fromIndex, int toIndex) {modCount++;int numMoved = elementCount - toIndex;System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);// Let gc do its workint newElementCount = elementCount - (toIndex-fromIndex);while (elementCount != newElementCount)elementData[--elementCount] = null;}//序列化的写入函数private void readObject(ObjectInputStream in)throws IOException, ClassNotFoundException {ObjectInputStream.GetField gfields = in.readFields();int count = gfields.get("elementCount", 0);Object[] data = (Object[])gfields.get("elementData", null);if (count < 0 || data == null || count > data.length) {throw new StreamCorruptedException("Inconsistent vector internals");}elementCount = count;elementData = data.clone();}//序列的private void writeObject(java.io.ObjectOutputStream s)throws java.io.IOException {final java.io.ObjectOutputStream.PutField fields = s.putFields();final Object[] data;synchronized (this) {fields.put("capacityIncrement", capacityIncrement);fields.put("elementCount", elementCount);data = elementData.clone();}fields.put("elementData", data);s.writeFields();}///这是返回ListIterator迭代器的方法,指定迭代的开始位置public synchronized ListIterator<E> listIterator(int index) {if (index < 0 || index > elementCount)throw new IndexOutOfBoundsException("Index: "+index);return new ListItr(index);}//开始位置位 0 定死public synchronized ListIterator<E> listIterator() {return new ListItr(0);}//这是返回iterator迭代器public synchronized Iterator<E> iterator() {return new Itr();}/*** AbstractList.Itr的优化版本 的迭代器实现类*/private class Itr implements Iterator<E> {int cursor; //要返回的下一个元素的索引int lastRet = -1; // 返回最后一个元素的索引; -1如果没有,int expectedModCount = modCount;//是否还有下一位public boolean hasNext() {return cursor != elementCount;}//返回下一位public E next() {synchronized (Vector.this) {checkForComodification();int i = cursor;if (i >= elementCount)throw new NoSuchElementException();cursor = i + 1;return elementData(lastRet = i);}}//移除当前所在光标的元素public void remove() {if (lastRet == -1)throw new IllegalStateException();synchronized (Vector.this) {checkForComodification();Vector.this.remove(lastRet);expectedModCount = modCount;}cursor = lastRet;lastRet = -1;}//这是jdk 1.8新增加的方法,重当前迭代位置开始 每个元素都执行 action的指定操作@Overridepublic void forEachRemaining(Consumer<? super E> action) {Objects.requireNonNull(action);synchronized (Vector.this) {final int size = elementCount;int i = cursor;if (i >= size) {return;}@SuppressWarnings("unchecked")final E[] elementData = (E[]) Vector.this.elementData;if (i >= elementData.length) {throw new ConcurrentModificationException();}//循环执行指定操作while (i != size && modCount == expectedModCount) {action.accept(elementData[i++]);}cursor = i;lastRet = i - 1;checkForComodification();}}final void checkForComodification() {if (modCount != expectedModCount)throw new ConcurrentModificationException();}}/*** AbstractList.ListItr的优化版本 ListIterator 实现*/final class ListItr extends Itr implements ListIterator<E> {//指定当前迭代的下一个位置的构造ListItr(int index) {super();cursor = index;}//是否还有上一位public boolean hasPrevious() {return cursor != 0;}//下一位在数组中的下标public int nextIndex() {return cursor;}//上一位在数组中的下标public int previousIndex() {return cursor - 1;}//返回上以为,并移动光标public E previous() {synchronized (Vector.this) {checkForComodification();int i = cursor - 1;if (i < 0)throw new NoSuchElementException();cursor = i;return elementData(lastRet = i);}}//修改当前迭代位置的值public void set(E e) {if (lastRet == -1)throw new IllegalStateException();synchronized (Vector.this) {checkForComodification();Vector.this.set(lastRet, e);}}//在当前迭代位置插入元素public void add(E e) {int i = cursor;synchronized (Vector.this) {checkForComodification();Vector.this.add(i, e);expectedModCount = modCount;}cursor = i + 1;lastRet = -1;}}//遍历执行 action 方法@Overridepublic synchronized void forEach(Consumer<? super E> action) {Objects.requireNonNull(action);final int expectedModCount = modCount;@SuppressWarnings("unchecked")final E[] elementData = (E[]) this.elementData;final int elementCount = this.elementCount;for (int i=0; modCount == expectedModCount && i < elementCount; i++) {action.accept(elementData[i]);}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}}@Override@SuppressWarnings("unchecked")public synchronized boolean removeIf(Predicate<? super E> filter) {Objects.requireNonNull(filter);// figure out which elements are to be removed// any exception thrown from the filter predicate at this stage// will leave the collection unmodifiedint removeCount = 0;final int size = elementCount;final BitSet removeSet = new BitSet(size);final int expectedModCount = modCount;for (int i=0; modCount == expectedModCount && i < size; i++) {@SuppressWarnings("unchecked")final E element = (E) elementData[i];if (filter.test(element)) {removeSet.set(i);removeCount++;}}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}// 移位幸存元素留在被移除元素留下的空间final boolean anyToRemove = removeCount > 0;if (anyToRemove) {final int newSize = size - removeCount;for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {i = removeSet.nextClearBit(i);elementData[j] = elementData[i];}for (int k=newSize; k < size; k++) {elementData[k] = null; // Let gc do its work}elementCount = newSize;if (modCount != expectedModCount) {throw new ConcurrentModificationException();}modCount++;}return anyToRemove;}@Override@SuppressWarnings("unchecked")//循环遍历 将执行operator返回的元素替换当前元素public synchronized void replaceAll(UnaryOperator<E> operator) {Objects.requireNonNull(operator);final int expectedModCount = modCount;final int size = elementCount;for (int i=0; modCount == expectedModCount && i < size; i++) {elementData[i] = operator.apply((E) elementData[i]);}if (modCount != expectedModCount) {throw new ConcurrentModificationException();}modCount++;}@SuppressWarnings("unchecked")@Override//这是给当前的数据进行排序的方法 Comparator 定义了排序的规则public synchronized void sort(Comparator<? super E> c) {final int expectedModCount = modCount;Arrays.sort((E[]) elementData, 0, elementCount, c);if (modCount != expectedModCount) {throw new ConcurrentModificationException();}modCount++;}//当前数据中创建Spliterator@Overridepublic Spliterator<E> spliterator() {return new VectorSpliterator<>(this, null, 0, -1, 0);}//与ArrayList Spliterator类似static final class VectorSpliterator<E> implements Spliterator<E> {private final Vector<E> list;private Object[] array;private int index; // 当前指数,在提前/拆分时修改private int fence; // -1直到使用;然后是最后一个索引private int expectedModCount; //栅栏设置时初始化/** 创建覆盖给定范围的新分裂器*/VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence,int expectedModCount) {this.list = list;this.array = array;this.index = origin;this.fence = fence;this.expectedModCount = expectedModCount;}private int getFence() { // 首次使用时初始化 返回数组的元素个数int hi;if ((hi = fence) < 0) {synchronized(list) {array = list.elementData;expectedModCount = list.modCount;//hi就等于 = list.elementCount 元素个数hi = fence = list.elementCount;}}return hi;}//重当前对象再分割一个 Spliteratorpublic Spliterator<E> trySplit() {// hi = list.elementCountint hi = getFence(),lo = index,//(lo + hi) / 2mid = (lo + hi) >>> 1;//看看是否还能拆分出一个 Spliterator 如果拆分不了返回nullreturn (lo >= mid) ? null :new VectorSpliterator<E>(list, array, lo, index = mid,expectedModCount);}@SuppressWarnings("unchecked")//将index + 1位执行 action定义的方法 这是jdk 1.8函数编程所提供出来的public boolean tryAdvance(Consumer<? super E> action) {int i;if (action == null)throw new NullPointerException();if (getFence() > (i = index)) {index = i + 1;action.accept((E)array[i]);if (list.modCount != expectedModCount)throw new ConcurrentModificationException();return true;}return false;}@SuppressWarnings("unchecked")//使用函数式编程 循环数组执行 actioinpublic void forEachRemaining(Consumer<? super E> action) {int i, hi; // 提升从循环访问和检查Vector<E> lst;Object[] a;if (action == null)throw new NullPointerException();if ((lst = list) != null) {if ((hi = fence) < 0) {synchronized(lst) {expectedModCount = lst.modCount;a = array = lst.elementData;hi = fence = lst.elementCount;}}elsea = array;if (a != null && (i = index) >= 0 && (index = hi) <= a.length) {//循环执行while (i < hi)action.accept((E) a[i++]);if (lst.modCount == expectedModCount)return;}}throw new ConcurrentModificationException();}//计算当前位置到末尾还有多少个元素public long estimateSize() {return (long) (getFence() - index);}public int characteristics() {return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;}}}
Vector和ArrayList的比较
| 底层结构 | 版本 | 线程安全(同步)效率 | 扩容倍数 | |
|---|---|---|---|---|
| ArrayList | 可变数组 | jdk1.2 | 不安全,效率高 | - 无参构造:第一次按10扩容,从第二次开始按1.5倍扩容 - 有参构造:按1.5倍扩容 |
| Vector | 可变数组 Object[] | jdk1.0 | 安全,效率不高 | - 无参构造:默认10,满后,按2倍扩容 - 有参构造:每次直接按2倍扩容 |
