zoukankan      html  css  js  c++  java
  • Vector源码解析

    Vector源码解析

        在之前文章ArrayList源码解析中分析了一下 ArrayList的源码和一些重要方法,现在对比 ArrayList,总结一下 Vector和 ArrayList的不同。

    1 Vector介绍

     1 public class Vector<E> 2 extends AbstractList<E> 3 implements List<E>, RandomAccess, Cloneable, java.io.Serializable 

    Vector 是矢量队列,它是JDK1.0版本添加的类。继承于AbstractList,实现了List, RandomAccess, Cloneable这些接口。
    Vector 继承了AbstractList,实现了List;所以,它是一个队列,支持相关的添加、删除、修改、遍历等功能。
    Vector 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在Vector中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。
    Vector 实现了Cloneable接口,即实现clone()函数。它能被克隆。
    和ArrayList不同,Vector中的操作是线程安全的。


    Vector与Collection关系如下图:

    2 Vector 变量

    与ArrayList相比,Vector多了一个capacityIncrement变量,该变量表示当容量不够时,容量自增的大小。

    3 Vector 构造方法

      其实两者在很多地方都是一样的,然而在构造方法上面, Vector比 ArrayList多了一个方法:

    1    public Vector(int initialCapacity, int capacityIncrement) {
    2         super();
    3         if (initialCapacity < 0)
    4             throw new IllegalArgumentException("Illegal Capacity: "+
    5                                                initialCapacity);
    6         this.elementData = new Object[initialCapacity];
    7         this.capacityIncrement = capacityIncrement;
    8     }

    主要是因为 ArrayList中没有 capacityIncrement这个变量, vector的这个构造方法,不仅能够指定初始化容量,还能指定当容量不够时,容量自增的大小。下面看扩容方法.

    4 Vector Api

     1 synchronized boolean        add(E object)
     2              void           add(int location, E object)
     3 synchronized boolean        addAll(Collection<? extends E> collection)
     4 synchronized boolean        addAll(int location, Collection<? extends E> collection)
     5 synchronized void           addElement(E object)
     6 synchronized int            capacity()
     7              void           clear()
     8 synchronized Object         clone()
     9              boolean        contains(Object object)
    10 synchronized boolean        containsAll(Collection<?> collection)
    11 synchronized void           copyInto(Object[] elements)
    12 synchronized E              elementAt(int location)
    13              Enumeration<E> elements()
    14 synchronized void           ensureCapacity(int minimumCapacity)
    15 synchronized boolean        equals(Object object)
    16 synchronized E              firstElement()
    17              E              get(int location)
    18 synchronized int            hashCode()
    19 synchronized int            indexOf(Object object, int location)
    20              int            indexOf(Object object)
    21 synchronized void           insertElementAt(E object, int location)
    22 synchronized boolean        isEmpty()
    23 synchronized E              lastElement()
    24 synchronized int            lastIndexOf(Object object, int location)
    25 synchronized int            lastIndexOf(Object object)
    26 synchronized E              remove(int location)
    27              boolean        remove(Object object)
    28 synchronized boolean        removeAll(Collection<?> collection)
    29 synchronized void           removeAllElements()
    30 synchronized boolean        removeElement(Object object)
    31 synchronized void           removeElementAt(int location)
    32 synchronized boolean        retainAll(Collection<?> collection)
    33 synchronized E              set(int location, E object)
    34 synchronized void           setElementAt(E object, int location)
    35 synchronized void           setSize(int length)
    36 synchronized int            size()
    37 synchronized List<E>        subList(int start, int end)
    38 synchronized <T> T[]        toArray(T[] contents)
    39 synchronized Object[]       toArray()
    40 synchronized String         toString()
    41 synchronized void           trimToSize()

    为了更了解Vector的原理,下面对Vector源码代码作出分析。

      1 package java.util;
      2 public class Vector<E>
      3     extends AbstractList<E>
      4     implements List<E>, RandomAccess, Cloneable, java.io.Serializable
      5 {
      6 
      7     // 保存Vector中数据的数组
      8     protected Object[] elementData;
      9     // 实际数据的数量
     10     protected int elementCount;
     11     // 容量增长系数
     12     protected int capacityIncrement;
     13     // Vector的序列版本号
     14     private static final long serialVersionUID = -2767605614048989439L;
     15     // Vector构造函数。默认容量是10。
     16     public Vector() {
     17         this(10);
     18     }
     19     // 指定Vector容量大小的构造函数
     20     public Vector(int initialCapacity) {
     21         this(initialCapacity, 0);
     22     }
     23     // 指定Vector"容量大小"和"增长系数"的构造函数
     24     public Vector(int initialCapacity, int capacityIncrement) {
     25         super();
     26         if (initialCapacity < 0)
     27             throw new IllegalArgumentException("Illegal Capacity: "+
     28                                                initialCapacity);
     29         // 新建一个数组,数组容量是initialCapacity
     30         this.elementData = new Object[initialCapacity];
     31         // 设置容量增长系数
     32         this.capacityIncrement = capacityIncrement;
     33     }
     34     // 指定集合的Vector构造函数。
     35     public Vector(Collection<? extends E> c) {
     36         // 获取“集合(c)”的数组,并将其赋值给elementData
     37         elementData = c.toArray();
     38         // 设置数组长度
     39         elementCount = elementData.length;
     40         // c.toArray might (incorrectly) not return Object[] (see 6260652)
     41         if (elementData.getClass() != Object[].class)
     42             elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
     43     }
     44     // 将数组Vector的全部元素都拷贝到数组anArray中
     45     public synchronized void copyInto(Object[] anArray) {
     46         System.arraycopy(elementData, 0, anArray, 0, elementCount);
     47     }
     48     // 将当前容量值设为 =实际元素个数
     49     public synchronized void trimToSize() {
     50         modCount++;
     51         int oldCapacity = elementData.length;
     52         if (elementCount < oldCapacity) {
     53             elementData = Arrays.copyOf(elementData, elementCount);
     54         }
     55     }
     56     // 确认“Vector容量”的帮助函数
     57     private void ensureCapacityHelper(int minCapacity) {
     58         int oldCapacity = elementData.length;
     59         // 当Vector的容量不足以容纳当前的全部元素,增加容量大小。
     60         // 若 容量增量系数>0(即capacityIncrement>0),则将容量增大当capacityIncrement
     61         // 否则,将容量增大一倍。
     62         if (minCapacity > oldCapacity) {
     63             Object[] oldData = elementData;
     64             int newCapacity = (capacityIncrement > 0) ?
     65                 (oldCapacity + capacityIncrement) : (oldCapacity * 2);
     66             if (newCapacity < minCapacity) {
     67                 newCapacity = minCapacity;
     68             }
     69             elementData = Arrays.copyOf(elementData, newCapacity);
     70         }
     71     }
     72     // 确定Vector的容量。
     73     public synchronized void ensureCapacity(int minCapacity) {
     74         // 将Vector的改变统计数+1
     75         modCount++;
     76         ensureCapacityHelper(minCapacity);
     77     }
     78     // 设置容量值为 newSize
     79     public synchronized void setSize(int newSize) {
     80         modCount++;
     81         if (newSize > elementCount) {
     82             // 若 "newSize 大于 Vector容量",则调整Vector的大小。
     83             ensureCapacityHelper(newSize);
     84         } else {
     85             // 若 "newSize 小于/等于 Vector容量",则将newSize位置开始的元素都设置为null
     86             for (int i = newSize ; i < elementCount ; i++) {
     87                 elementData[i] = null;
     88             }
     89         }
     90         elementCount = newSize;
     91     }
     92     // 返回“Vector的总的容量”
     93     public synchronized int capacity() {
     94         return elementData.length;
     95     }
     96     // 返回“Vector的实际大小”,即Vector中元素个数
     97     public synchronized int size() {
     98         return elementCount;
     99     }
    100     // 判断Vector是否为空
    101     public synchronized boolean isEmpty() {
    102         return elementCount == 0;
    103     }
    104     // 返回“Vector中全部元素对应的Enumeration”
    105     public Enumeration<E> elements() {
    106         // 通过匿名类实现Enumeration
    107         return new Enumeration<E>() {
    108             int count = 0;
    109             // 是否存在下一个元素
    110             public boolean hasMoreElements() {
    111                 return count < elementCount;
    112             }
    113             // 获取下一个元素
    114             public E nextElement() {
    115                 synchronized (Vector.this) {
    116                     if (count < elementCount) {
    117                         return (E)elementData[count++];
    118                     }
    119                 }
    120                 throw new NoSuchElementException("Vector Enumeration");
    121             }
    122         };
    123     }
    124     // 返回Vector中是否包含对象(o)
    125     public boolean contains(Object o) {
    126         return indexOf(o, 0) >= 0;
    127     }
    128     // 从index位置开始向后查找元素(o)。
    129     // 若找到,则返回元素的索引值;否则,返回-1
    130     public synchronized int indexOf(Object o, int index) {
    131         if (o == null) {
    132             // 若查找元素为null,则正向找出null元素,并返回它对应的序号
    133             for (int i = index ; i < elementCount ; i++)
    134             if (elementData[i]==null)
    135                 return i;
    136         } else {
    137             // 若查找元素不为null,则正向找出该元素,并返回它对应的序号
    138             for (int i = index ; i < elementCount ; i++)
    139             if (o.equals(elementData[i]))
    140                 return i;
    141         }
    142         return -1;
    143     }
    144     // 查找并返回元素(o)在Vector中的索引值
    145     public int indexOf(Object o) {
    146         return indexOf(o, 0);
    147     }
    148     // 从后向前查找元素(o)。并返回元素的索引
    149     public synchronized int lastIndexOf(Object o) {
    150         return lastIndexOf(o, elementCount-1);
    151     }
    152     // 从后向前查找元素(o)。开始位置是从前向后的第index个数;
    153     // 若找到,则返回元素的“索引值”;否则,返回-1。
    154     public synchronized int lastIndexOf(Object o, int index) {
    155         if (index >= elementCount)
    156             throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
    157         if (o == null) {
    158             // 若查找元素为null,则反向找出null元素,并返回它对应的序号
    159             for (int i = index; i >= 0; i--)
    160             if (elementData[i]==null)
    161                 return i;
    162         } else {
    163             // 若查找元素不为null,则反向找出该元素,并返回它对应的序号
    164             for (int i = index; i >= 0; i--)
    165             if (o.equals(elementData[i]))
    166                 return i;
    167         }
    168         return -1;
    169     }
    170     // 返回Vector中index位置的元素。
    171     // 若index月结,则抛出异常
    172     public synchronized E elementAt(int index) {
    173         if (index >= elementCount) {
    174             throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
    175         }
    176         return (E)elementData[index];
    177     }
    178     // 获取Vector中的第一个元素。
    179     // 若失败,则抛出异常!
    180     public synchronized E firstElement() {
    181         if (elementCount == 0) {
    182             throw new NoSuchElementException();
    183         }
    184         return (E)elementData[0];
    185     }
    186     // 获取Vector中的最后一个元素。
    187     // 若失败,则抛出异常!
    188     public synchronized E lastElement() {
    189         if (elementCount == 0) {
    190             throw new NoSuchElementException();
    191         }
    192         return (E)elementData[elementCount - 1];
    193     }
    194     // 设置index位置的元素值为obj
    195     public synchronized void setElementAt(E obj, int index) {
    196         if (index >= elementCount) {
    197             throw new ArrayIndexOutOfBoundsException(index + " >= " +
    198                                  elementCount);
    199         }
    200         elementData[index] = obj;
    201     }
    202     // 删除index位置的元素
    203     public synchronized void removeElementAt(int index) {
    204         modCount++;
    205         if (index >= elementCount) {
    206             throw new ArrayIndexOutOfBoundsException(index + " >= " +
    207                                  elementCount);
    208         } else if (index < 0) {
    209             throw new ArrayIndexOutOfBoundsException(index);
    210         }
    211         int j = elementCount - index - 1;
    212         if (j > 0) {
    213             System.arraycopy(elementData, index + 1, elementData, index, j);
    214         }
    215         elementCount--;
    216         elementData[elementCount] = null; /* to let gc do its work */
    217     }
    218     // 在index位置处插入元素(obj)
    219     public synchronized void insertElementAt(E obj, int index) {
    220         modCount++;
    221         if (index > elementCount) {
    222             throw new ArrayIndexOutOfBoundsException(index
    223                                  + " > " + elementCount);
    224         }
    225         ensureCapacityHelper(elementCount + 1);
    226         System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
    227         elementData[index] = obj;
    228         elementCount++;
    229     }
    230     // 将“元素obj”添加到Vector末尾
    231     public synchronized void addElement(E obj) {
    232         modCount++;
    233         ensureCapacityHelper(elementCount + 1);
    234         elementData[elementCount++] = obj;
    235     }
    236     // 在Vector中查找并删除元素obj。
    237     // 成功的话,返回true;否则,返回false。
    238     public synchronized boolean removeElement(Object obj) {
    239         modCount++;
    240         int i = indexOf(obj);
    241         if (i >= 0) {
    242             removeElementAt(i);
    243             return true;
    244         }
    245         return false;
    246     }
    247     // 删除Vector中的全部元素
    248     public synchronized void removeAllElements() {
    249         modCount++;
    250         // 将Vector中的全部元素设为null
    251         for (int i = 0; i < elementCount; i++)
    252             elementData[i] = null;
    253         elementCount = 0;
    254     }
    255     // 克隆函数
    256     public synchronized Object clone() {
    257         try {
    258             Vector<E> v = (Vector<E>) super.clone();
    259             // 将当前Vector的全部元素拷贝到v中
    260             v.elementData = Arrays.copyOf(elementData, elementCount);
    261             v.modCount = 0;
    262             return v;
    263         } catch (CloneNotSupportedException e) {
    264             // this shouldn't happen, since we are Cloneable
    265             throw new InternalError();
    266         }
    267     }
    268     // 返回Object数组
    269     public synchronized Object[] toArray() {
    270         return Arrays.copyOf(elementData, elementCount);
    271     }
    272     // 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型
    273     public synchronized <T> T[] toArray(T[] a) {
    274         // 若数组a的大小 < Vector的元素个数;
    275         // 则新建一个T[]数组,数组大小是“Vector的元素个数”,并将“Vector”全部拷贝到新数组中
    276         if (a.length < elementCount)
    277             return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
    278         // 若数组a的大小 >= Vector的元素个数;
    279         // 则将Vector的全部元素都拷贝到数组a中。
    280     System.arraycopy(elementData, 0, a, 0, elementCount);
    281         if (a.length > elementCount)
    282             a[elementCount] = null;
    283         return a;
    284     }
    285     // 获取index位置的元素
    286     public synchronized E get(int index) {
    287         if (index >= elementCount)
    288             throw new ArrayIndexOutOfBoundsException(index);
    289         return (E)elementData[index];
    290     }
    291     // 设置index位置的值为element。并返回index位置的原始值
    292     public synchronized E set(int index, E element) {
    293         if (index >= elementCount)
    294             throw new ArrayIndexOutOfBoundsException(index);
    295         Object oldValue = elementData[index];
    296         elementData[index] = element;
    297         return (E)oldValue;
    298     }
    299     // 将“元素e”添加到Vector最后。
    300     public synchronized boolean add(E e) {
    301         modCount++;
    302         ensureCapacityHelper(elementCount + 1);
    303         elementData[elementCount++] = e;
    304         return true;
    305     }
    306     // 删除Vector中的元素o
    307     public boolean remove(Object o) {
    308         return removeElement(o);
    309     }
    310     // 在index位置添加元素element
    311     public void add(int index, E element) {
    312         insertElementAt(element, index);
    313     }
    314     // 删除index位置的元素,并返回index位置的原始值
    315     public synchronized E remove(int index) {
    316         modCount++;
    317         if (index >= elementCount)
    318             throw new ArrayIndexOutOfBoundsException(index);
    319         Object oldValue = elementData[index];
    320         int numMoved = elementCount - index - 1;
    321         if (numMoved > 0)
    322             System.arraycopy(elementData, index+1, elementData, index,
    323                      numMoved);
    324         elementData[--elementCount] = null; // Let gc do its work
    325         return (E)oldValue;
    326     }
    327     // 清空Vector
    328     public void clear() {
    329         removeAllElements();
    330     }
    331     // 返回Vector是否包含集合c
    332     public synchronized boolean containsAll(Collection<?> c) {
    333         return super.containsAll(c);
    334     }
    335     // 将集合c添加到Vector中
    336     public synchronized boolean addAll(Collection<? extends E> c) {
    337         modCount++;
    338         Object[] a = c.toArray();
    339         int numNew = a.length;
    340         ensureCapacityHelper(elementCount + numNew);
    341         // 将集合c的全部元素拷贝到数组elementData中
    342         System.arraycopy(a, 0, elementData, elementCount, numNew);
    343         elementCount += numNew;
    344         return numNew != 0;
    345     }
    346     // 删除集合c的全部元素
    347     public synchronized boolean removeAll(Collection<?> c) {
    348         return super.removeAll(c);
    349     }
    350     // 删除“非集合c中的元素”
    351     public synchronized boolean retainAll(Collection<?> c)  {
    352         return super.retainAll(c);
    353     }
    354     // 从index位置开始,将集合c添加到Vector中
    355     public synchronized boolean addAll(int index, Collection<? extends E> c) {
    356         modCount++;
    357         if (index < 0 || index > elementCount)
    358             throw new ArrayIndexOutOfBoundsException(index);
    359         Object[] a = c.toArray();
    360         int numNew = a.length;
    361         ensureCapacityHelper(elementCount + numNew);
    362         int numMoved = elementCount - index;
    363         if (numMoved > 0)
    364         System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
    365         System.arraycopy(a, 0, elementData, index, numNew);
    366         elementCount += numNew;
    367         return numNew != 0;
    368     }
    369     // 返回两个对象是否相等
    370     public synchronized boolean equals(Object o) {
    371         return super.equals(o);
    372     }
    373     // 计算哈希值
    374     public synchronized int hashCode() {
    375         return super.hashCode();
    376     }
    377     // 调用父类的toString()
    378     public synchronized String toString() {
    379         return super.toString();
    380     }
    381     // 获取Vector中fromIndex(包括)到toIndex(不包括)的子集
    382     public synchronized List<E> subList(int fromIndex, int toIndex) {
    383         return Collections.synchronizedList(super.subList(fromIndex, toIndex), this);
    384     }
    385     // 删除Vector中fromIndex到toIndex的元素
    386     protected synchronized void removeRange(int fromIndex, int toIndex) {
    387         modCount++;
    388         int numMoved = elementCount - toIndex;
    389         System.arraycopy(elementData, toIndex, elementData, fromIndex,
    390                          numMoved);
    391         // Let gc do its work
    392         int newElementCount = elementCount - (toIndex-fromIndex);
    393         while (elementCount != newElementCount)
    394             elementData[--elementCount] = null;
    395     }
    396     // java.io.Serializable的写入函数
    397     private synchronized void writeObject(java.io.ObjectOutputStream s)
    398         throws java.io.IOException {
    399         s.defaultWriteObject();
    400     }
    401 }

    总结:
    (01) Vector实际上是通过一个数组去保存数据的。当我们构造Vecotr时;若使用默认构造函数,则Vector的默认容量大小是10。
    (02) 当Vector容量不足以容纳全部元素时,Vector的容量会增加。若容量增加系数 >0,则将容量的值增加“容量增加系数”;否则,将容量大小增加一倍。
    (03) Vector的克隆函数,即是将全部元素克隆到一个数组中。
     第3部分 Vector遍历方式
    Vector支持4种遍历方式。建议使用下面的第二种去遍历Vector,因为效率问题。

     1 (01) 第一种,通过迭代器遍历。即通过Iterator去遍历。
     2 Integer value = null;
     3 int size = vec.size();
     4 for (int i=0; i<size; i++) {
     5     value = (Integer)vec.get(i);        
     6 }
     7 (02) 第二种,随机访问,通过索引值去遍历。
     8 由于Vector实现了RandomAccess接口,它支持通过索引值去随机访问元素。
     9 Integer value = null;
    10 int size = vec.size();
    11 for (int i=0; i<size; i++) {
    12     value = (Integer)vec.get(i);        
    13 }
    14 (03) 第三种,另一种for循环。如下:
    15 Integer value = null;
    16 for (Integer integ:vec) {
    17     value = integ;
    18 }
    19 (04) 第四种,Enumeration遍历。如下:
    20 Integer value = null;
    21 Enumeration enu = vec.elements();
    22 while (enu.hasMoreElements()) {
    23     value = (Integer)enu.nextElement();
    24 }
    25  
  • 相关阅读:
    Eclipse中配置约束
    c++ 虚函数
    cocos3 menu
    cocos3 封装一个ball
    cocos3 内存管理机制
    cocos3 多文件拆分cocos
    cocos3 labelttf
    cocos3 messagebox
    cocos3 log
    cocos3 director sprite scene之间的关系
  • 原文地址:https://www.cnblogs.com/xsyfl/p/6920321.html
Copyright © 2011-2022 走看看