• 【Java集合源码剖析】Vector源码剖析


    转载请注明出处:http://blog.csdn.net/ns_code/article/details/35793865

     

    Vector简介

        Vector也是基于数组实现的,是一个动态数组,其容量能自动增长。

        Vector是JDK1.0引入了,它的很多实现方法都加入了同步语句,因此是线程安全的(其实也只是相对安全,有些时候还是要加入同步语句来保证线程的安全),可以用于多线程环境。

        Vector没有丝线Serializable接口,因此它不支持序列化,实现了Cloneable接口,能被克隆,实现了RandomAccess接口,支持快速随机访问。

    Vector源码剖析

        Vector的源码如下(加入了比较详细的注释):

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

    几点总结

        Vector的源码实现总体与ArrayList类似,关于Vector的源码,给出如下几点总结:

        1、Vector有四个不同的构造方法。无参构造方法的容量为默认值10,仅包含容量的构造方法则将容量增长量(从源码中可以看出容量增长量的作用,第二点也会对容量增长量详细说)明置为0。

        2、注意扩充容量的方法ensureCapacityHelper。与ArrayList相同,Vector在每次增加元素(可能是1个,也可能是一组)时,都要调用该方法来确保足够的容量。当容量不足以容纳当前的元素个数时,就先看构造方法中传入的容量增长量参数CapacityIncrement是否为0,如果不为0,就设置新的容量为就容量加上容量增长量,如果为0,就设置新的容量为旧的容量的2倍,如果设置后的新容量还不够,则直接新容量设置为传入的参数(也就是所需的容量),而后同样用Arrays.copyof()方法将元素拷贝到新的数组。

        3、很多方法都加入了synchronized同步语句,来保证线程安全。

        4、同样在查找给定元素索引值等的方法中,源码都将该元素的值分为null和不为null两种情况处理,Vector中也允许元素为null。

        5、其他很多地方都与ArrayList实现大同小异,Vector现在已经基本不再使用。

  • 相关阅读:
    CentOS7和Ubuntu下安装Docker & Docker-Compose
    【译】ModSecurity
    【译】ModSecurity事务生命周期
    开源WAF工具ModSecurity
    RHEL/CentOS 安装最新版Nginx
    Linux流量监控工具iftop & nload
    Docker安全扫描工具之docker-bench-security
    wireshark抓包如何查看视频分辨率和码率
    【译】如何使用docker-compose安装anchore
    Docker安全扫描工具之DockerScan
  • 原文地址:https://www.cnblogs.com/NullPointException/p/5069513.html
Copyright © 2020-2023  润新知