一、概述
1、介绍
Java里古老的容器,JDK1.0版本添加的类,矢量队列,线程安全的,使用关键字synchronized,保证方法同步。
底层维护一个 Object 数组,初始长度为10,默认情况扩容为原来数组的 2 倍。也可以指定扩容步长。其他的和 ArrayList 没有太大区别。
扩容原理:
2、API的使用
synchronized boolean add(E object)
void add(int location, E object)
synchronized boolean addAll(Collection<? extends E> collection)
synchronized boolean addAll(int location, Collection<? extends E> collection)
synchronized void addElement(E object)
synchronized int capacity()
void clear()
synchronized Object clone()
boolean contains(Object object)
synchronized boolean containsAll(Collection<?> collection)
synchronized void copyInto(Object[] elements)
synchronized E elementAt(int location)
Enumeration<E> elements()
synchronized void ensureCapacity(int minimumCapacity)
synchronized boolean equals(Object object)
synchronized E firstElement()
E get(int location)
synchronized int hashCode()
synchronized int indexOf(Object object, int location)
int indexOf(Object object)
synchronized void insertElementAt(E object, int location)
synchronized boolean isEmpty()
synchronized E lastElement()
synchronized int lastIndexOf(Object object, int location)
synchronized int lastIndexOf(Object object)
synchronized E remove(int location)
boolean remove(Object object)
synchronized boolean removeAll(Collection<?> collection)
synchronized void removeAllElements()
synchronized boolean removeElement(Object object)
synchronized void removeElementAt(int location)
synchronized boolean retainAll(Collection<?> collection)
synchronized E set(int location, E object)
synchronized void setElementAt(E object, int location)
synchronized void setSize(int length)
synchronized int size()
synchronized List<E> subList(int start, int end)
synchronized <T> T[] toArray(T[] contents)
synchronized Object[] toArray()
synchronized String toString()
synchronized void trimToSize()
3、四种遍历方式
①迭代器
public class Main {public static void main(String[] args) {Vector<Integer> vector = new Vector<>();vector.add(1);vector.add(3);vector.add(2);final Iterator<Integer> iterator = vector.iterator();while (iterator.hasNext()) {System.out.println(iterator.next());}}}
②随机访问
由于Vector实现了RandomAccess接口,它支持通过索引值去随机访问元素。
public class Main {public static void main(String[] args) {Vector<Integer> vector = new Vector<>();vector.add(1);vector.add(3);vector.add(2);for (int i = 0; i < vector.size(); i++) {System.out.println(vector.get(i));}}}
③增强for循环
public class Main {public static void main(String[] args) {Vector<Integer> vector = new Vector<>();vector.add(1);vector.add(3);vector.add(2);for (Integer integer : vector) {System.out.println(integer);}}}
④Enumeration遍历
枚举,这也是Vector特有的遍历方式。
public class Main {public static void main(String[] args) {Vector<Integer> vector = new Vector<>();vector.add(1);vector.add(3);vector.add(2);final Enumeration<Integer> elements = vector.elements();while (elements.hasMoreElements()) {System.out.println(elements.nextElement());}}}
二、类源码
1、类声明
源码示例:
* @author Lee Boynton* @author Jonathan Payne* @see Collection* @see LinkedList* @since JDK1.0*/public class Vector<E>extends AbstractList<E>implements List<E>, RandomAccess, Cloneable, java.io.Serializable{}
实现了RandmoAccess 接口,为List提供快速随机访问功能。
实现了 Cloneable 接口,复写clone()函数,表示它能被克隆。
实现了Serializable 接口,标识该类可序列化。
2、类属性
源码示例:读一下源码中的英文注释。
// 动态数组.默认初始化大小为 10protected Object[] elementData;// 动态数组的实际大小.集合中实际元素的个数protected int elementCount;// 扩容步长.默认为0.若指定了,则按指定长度扩容protected int capacityIncrement;// 可序列化的UID号private static final long serialVersionUID = -2767605614048989439L;
3、类构造器
源码示例:
public Vector(int initialCapacity, int capacityIncrement) {super();if (initialCapacity < 0)throw new IllegalArgumentException(\"Illegal Capacity: \"+initialCapacity);// 新建一个数组,数组容量是initialCapacitythis.elementData = new Object[initialCapacity];// 设置扩容步长this.capacityIncrement = capacityIncrement;}// 默认的扩容步长为 0public Vector(int initialCapacity) {this(initialCapacity, 0);}// 默认构造器初始大小为 10public Vector() {this(10);}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);}
4、add()方法
源码示例:扩容原理
// 方法是同步的public synchronized boolean add(E e) {// 记录修改次数+1modCount++;// 判断是否需要扩容ensureCapacityHelper(elementCount + 1);// 将新增的元素 e 放到elementData数组中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 codeint 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);}
5、addElement()方法
源码示例:
// 与add()方法相同public synchronized void addElement(E obj) {modCount++;ensureCapacityHelper(elementCount + 1);elementData[elementCount++] = obj;}
6、get()方法
源码示例:
public synchronized E get(int index) {if (index >= elementCount)throw new ArrayIndexOutOfBoundsException(index);// 通过数组下标获取元素return elementData(index);}
7、insertElementAt()方法
源码示例:在指定位置插入元素
// 在index位置处插入元素(obj)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);// 将元素插入到index的位置elementData[index] = obj;elementCount++;}
8、其他方法
源码示例:
// 将数组Vector的全部元素都拷贝到数组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) {// 将数组的元素全部拷贝到实际容量大小的数组中去elementData = Arrays.copyOf(elementData, elementCount);}}// 确定Vector的容量。public synchronized void ensureCapacity(int minCapacity) {if (minCapacity > 0) {modCount++;ensureCapacityHelper(minCapacity);}}// 设置容量值为 newSizepublic synchronized void setSize(int newSize) {modCount++;if (newSize > elementCount) {// 调整Vector的大小ensureCapacityHelper(newSize);} else {// 将从 newSize 位置开始的元素都设置为nullfor (int i = newSize ; i < elementCount ; i++) {elementData[i] = null;}}elementCount = newSize;}// 返回Vector总容量大小public synchronized int capacity() {return elementData.length;}// 返回Vector中实际元素个数public synchronized int size() {return elementCount;}// 判断Vector是否为空public synchronized boolean isEmpty() {return elementCount == 0;}// 返回Vector中全部元素对应的Enumerationpublic Enumeration<E> elements() {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\");}};}// 是否包含对象(o)public boolean contains(Object o) {return indexOf(o, 0) >= 0;}// 从 0 开始搜索 opublic int indexOf(Object o) {return indexOf(o, 0);}// 从 index 开始搜索 opublic synchronized int indexOf(Object o, int index) {if (o == null) {// 搜索 o == null 的情况for (int i = index ; i < elementCount ; i++)if (elementData[i]==null)return i;} else {// 若 o!=null 搜索 o 返回对应的索引for (int i = index ; i < elementCount ; i++)if (o.equals(elementData[i]))return i;}// 找不到,返回 -1return -1;}// 从后向前查找元素(o)。并返回元素的索引public synchronized int lastIndexOf(Object o) {return lastIndexOf(o, elementCount - 1);}// 从后向前查找元素(o)。开始位置是从前向后的第index个数;public synchronized int lastIndexOf(Object o, int index) {if (index >= elementCount)throw new IndexOutOfBoundsException(index + \" >= \" + elementCount);if (o == null) {// 若查找元素为null,则反向找出null元素,并返回它对应的序号for (int i = index; i >= 0; i--)if (elementData[i] == null)return i;} else {// 若查找元素不为null,则反向找出该元素,并返回它对应的序号for (int i = index; i >= 0; i--)if (o.equals(elementData[i]))return i;}// 找不到,返回 -1return -1;}// 返回index位置的元素。public synchronized E elementAt(int index) {// 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 (E) elementData[elementCount - 1];}// 设置index位置的元素值为objpublic synchronized void setElementAt(E obj, int index) {if (index >= elementCount) {throw new ArrayIndexOutOfBoundsException(index + \" >= \" +elementCount);}elementData[index] = obj;}// 删除index位置的元素public synchronized void removeElementAt(int index) {modCount++;if (index >= elementCount) {throw new ArrayIndexOutOfBoundsException(index + \" >= \" +elementCount);}else if (index < 0) {throw new ArrayIndexOutOfBoundsException(index);}int j = elementCount - index - 1;if (j > 0) {System.arraycopy(elementData, index + 1, elementData, index, j);}elementCount--;elementData[elementCount] = null; /* to let gc do its work */}// 在Vector中查找并删除元素obj。public synchronized boolean removeElement(Object obj) {modCount++;// 找到 objint i = indexOf(obj);if (i >= 0) {// 存在,移除,返回trueremoveElementAt(i);return true;}// 失败,返回falsereturn false;}// 删除Vector中的全部元素public synchronized void removeAllElements() {modCount++;// Let gc do its work// 将Vector中的全部元素设为nullfor (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);}}// 返回将vector转化为Object数组public synchronized Object[] toArray() {return Arrays.copyOf(elementData, elementCount);}// 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型public synchronized <T> T[] toArray(T[] a) {// 若数组a的大小 < Vector的元素个数;// 则新建一个T[]数组,数组大小是“Vector的元素个数”,并将“Vector”全部拷贝到新数组中if (a.length < elementCount)return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());// 若数组a的大小 >= Vector的元素个数;// 则将Vector的全部元素都拷贝到数组a中。System.arraycopy(elementData, 0, a, 0, elementCount);if (a.length > elementCount)a[elementCount] = null;return a;}// 设置index位置的值为element。并返回index位置的原始值public synchronized E set(int index, E element) {if (index >= elementCount)throw new ArrayIndexOutOfBoundsException(index);Object oldValue = elementData[index];elementData[index] = element;return (E) oldValue;}// 删除Vector中的元素opublic boolean remove(Object o) {return removeElement(o);}// 删除index位置的元素,并返回index位置的原始值public synchronized E remove(int index) {modCount++;if (index >= elementCount)throw new ArrayIndexOutOfBoundsException(index);// 找到元素Object 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 (E) oldValue;}// 清空Vectorpublic void clear() {removeAllElements();}// 返回Vector是否包含集合cpublic synchronized boolean containsAll(Collection<?> c) {return super.containsAll(c);}// 将集合c添加到Vector中public synchronized boolean addAll(Collection<? extends E> c) {modCount++;Object[] a = c.toArray();int numNew = a.length;ensureCapacityHelper(elementCount + numNew);// 将集合c的全部元素拷贝到数组elementData中System.arraycopy(a, 0, elementData, elementCount, numNew);elementCount += numNew;return numNew != 0;}// 删除集合c的全部元素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;}// 返回两个对象是否相等public synchronized boolean equals(Object o) {return super.equals(o);}// 计算哈希值public synchronized int hashCode() {return super.hashCode();}// 调用父类的toString()public synchronized String toString() {return super.toString();}// 获取[fromIndex,toIndex)子列表,同步的public synchronized List<E> subList(int fromIndex, int toIndex) {return Collections.synchronizedList(super.subList(fromIndex, toIndex),this);}// 删除Vector中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;}// java.io.Serializable的写入函数.用于序列化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();}