JDK源码学习系列06----Vector
1.Vector简介
Vector的内部是数组实现的,它和ArrayList非常相似,最大的不同就是 Vector 是线程安全(同步)的。
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
Vector继承于AbstractList,实现了List, RandomAccess, Cloneable,java.io.Serializable这些接口。
Vector 继承了AbstractList,实现了List ,支持相关的添加、删除、修改、遍历等功能。
Vector 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在Vector 中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。
Vector 实现了Cloneable接口,即实现clone()函数。它能被克隆。
2.Vector的成员变量
protected Object[] elementData;//内部实现数组 protected int elementCount;//vector内容的实际长度 protected int capacityIncrement;//容量递增值 private static final long serialVersionUID = -2767605614048989439L;//序列id
3.Vector的构造函数
public Vector(int initialCapacity, int capacityIncrement) { super(); if (initialCapacity < 0)//若容量递增值小于0,则抛出异常 throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity];//elementData数组,容量为initialCapacity this.capacityIncrement = capacityIncrement;//扩容时容量的递增值 } public Vector(int initialCapacity) { this(initialCapacity, 0); } public Vector() {// Vector的默认容量为10 this(10); } public Vector(Collection<? extends E> c) {//初始化一个包含集合的Vector 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.Vector的成员函数
很多成员函数都用synchronized关键字修饰了的,即表示是同步的,线程安全的。关于synchronized关键字,请见:java synchronized 关键字 。
public synchronized void copyInto(Object[] anArray) {//把Vector复制到anArray数组中 System.arraycopy(elementData, 0, anArray, 0, elementCount);//数组的复制都是用的System.arraycopy(),Arrays.copyof()的内部也是用的System.arraycopy(). } public synchronized void trimToSize() {//把容量缩小到刚好等于vector的实际长度 modCount++;//!!线程安全的类的源码中也有统计结构变化次数的modCount int oldCapacity = elementData.length; if (elementCount < oldCapacity) { elementData = Arrays.copyOf(elementData, elementCount); } } public synchronized void ensureCapacity(int minCapacity) {//扩容,调用确认扩容帮助的方法 modCount++; ensureCapacityHelper(minCapacity); } private void ensureCapacityHelper(int minCapacity) {//确认扩容的帮助方法 int oldCapacity = elementData.length; if (minCapacity > oldCapacity) {//<strong>①如果传入的参数大于原始容量:如果容量增幅值大于0,则增加容量增幅值;若容量增幅值小于0,则容量直接扩大两倍</strong> Object[] oldData = elementData; int newCapacity = (capacityIncrement > 0) ? (oldCapacity + capacityIncrement) : (oldCapacity * 2); if (newCapacity < minCapacity) {//<strong>②如果向上面那样增加后还是小于传入的参数:参数作为新的容量</strong> newCapacity = minCapacity; } elementData = Arrays.copyOf(elementData, newCapacity); } } public synchronized void setSize(int newSize) {//设置容量值 modCount++; if (newSize > elementCount) {//若容量值参数大于原始的容量,则扩容 ensureCapacityHelper(newSize); } else {//若传入的容量值小于原始容量,即<strong>缩容:多出的后面部分全部置为null</strong> 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; } public Enumeration<E> elements() {//<span style="line-height: 1.5; font-family: 'Courier New'; white-space: pre-wrap; ">返回Vector中全部元素对应的Enumeration</span> return new Enumeration<E>() {//<span style="line-height: 1.5; font-family: 'Courier New'; white-space: pre-wrap; ">通过匿名内部类实现Enumeration</span> int count = 0; public boolean hasMoreElements() {//是否存在下一元素 return count < elementCount; } public E nextElement() {//获取下一元素 synchronized (Vector.this) { if (count < elementCount) { return (E)elementData[count++]; } } throw new NoSuchElementException("Vector Enumeration"); } }; } public boolean contains(Object o) {//是否包含 return indexOf(o, 0) >= 0; } public int indexOf(Object o) {//定位索引 return indexOf(o, 0); } public synchronized int indexOf(Object o, int index) { if (o == null) {//一定不要忽略了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; } 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) {//不要忘了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; } return -1; } public synchronized E elementAt(int index) {//得到某个索引对应的值 if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } return (E)elementData[index];//即数组下标对应的值,注意向下转型 } public synchronized E firstElement() {//获取第一个元素 if (elementCount == 0) {//!!!!!!!!!!!特殊情况的考虑啊!!!!!!!!!!!! throw new NoSuchElementException();//若vector为空则抛出异常 } return (E)elementData[0]; } public synchronized E lastElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return (E)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); } int j = elementCount - index - 1;//需要移动的位于index后的元素个数 if (j > 0) { System.arraycopy(elementData, index + 1, elementData, index, j); } elementCount--; elementData[elementCount] = null;//gc会自动回收掉最后一个空出来的位置 } 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位置移到从index+1,移动的长度为elementCount-index.即空出一个来插入元素 elementData[index] = obj; elementCount++; } public synchronized void addElement(E obj) {//在vector尾部添加元素 modCount++; ensureCapacityHelper(elementCount + 1);//添加元素时先扩容 elementData[elementCount++] = obj; } public synchronized boolean removeElement(Object obj) {//移除某个元素,先得到元素的索引在根据索引移除 modCount++; int i = indexOf(obj); if (i >= 0) { removeElementAt(i); return true; } return false; } public synchronized void removeAllElements() {//移除所有,把每个元素都置为null modCount++; // Let gc do its work for (int i = 0; i < elementCount; i++) elementData[i] = null; elementCount = 0; } public synchronized Object clone() {//克隆Vector try { Vector<E> v = (Vector<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, elementCount);//将vector中的元素全部拷贝到v中 v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } public synchronized Object[] toArray() {// 返回数组 return Arrays.copyOf(elementData, elementCount); } public synchronized <T> T[] toArray(T[] a) { if (a.length < elementCount)//若a的长度小于vector的实际长度,则新建一个长度为elementCount的数组 return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass()); System.arraycopy(elementData, 0, a, 0, elementCount); if (a.length > elementCount)//多出的置为null a[elementCount] = null; return a; } public synchronized E get(int index) {//根据索引得到元素 if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return (E)elementData[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; } public synchronized boolean add(E e) {//在尾部添加一元素,成功了才返回true 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); 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 work return (E)oldValue; } public void clear() {//清空vector removeAllElements(); } public synchronized boolean containsAll(Collection<?> c) { return super.containsAll(c); } public synchronized boolean addAll(Collection<? extends E> c) {//将集合添加到vector的尾部,先扩容再利用System.arraycopy() modCount++; Object[] a = c.toArray();//把集合先变成数组 int numNew = a.length; ensureCapacityHelper(elementCount + numNew); System.arraycopy(a, 0, elementData, elementCount, numNew); elementCount += numNew; return numNew != 0; } public synchronized boolean removeAll(Collection<?> c) { return super.removeAll(c); } public synchronized boolean retainAll(Collection<?> c) { return super.retainAll(c); } 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 int hashCode() {//计算hash值 return super.hashCode(); } public synchronized String toString() { return super.toString(); } public synchronized List<E> subList(int fromIndex, int toIndex) {//截取从fromIndex到toIndex,不包含toIndex return Collections.synchronizedList(super.subList(fromIndex, toIndex), this); } protected synchronized void removeRange(int fromIndex, int toIndex) {//利用System.arraycopy()来移动数组达到移除元素的作用 modCount++; int numMoved = elementCount - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do its work int newElementCount = elementCount - (toIndex-fromIndex); while (elementCount != newElementCount) elementData[--elementCount] = null; } private synchronized void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); }
5.总结
a.Vector的内部是数组实现的。
b.Vector是线程安全(同步)的。
c.Vector默认长度为10,扩容时需要参考容量增幅值,若容量增幅值大于0,则扩容为 原容量+容量增幅值;若容量增幅值小于 0,则扩容为 2*原容量。若根据容量增幅值扩容后 还是小于传入的新容量参数值,则容量扩为传入的新参数。
JDK源码学习系列06----Vector,布布扣,bubuko.com