Vector源码分析

vector的底层存储结构是数组,和ArrayList一样,不同的是vector是线程安全的,而ArrayList不是线程安全的。进入源码分析

1.属性

 /**
     * The array buffer into which the components of the vector are
     * stored. The capacity of the vector is the length of this array buffer,
     * and is at least large enough to contain all the vector's elements.
     *
     * <p>Any array elements following the last element in the Vector are null.
     *
     * @serial
     */
//vector的底层存储结构,vector中的元素就是存储在这个数组中 protected Object[] elementData; /** * The number of valid components in this {@code Vector} object. * Components {@code elementData[0]} through * {@code elementData[elementCount-1]} are the actual items. * * @serial */
//数组中元素的数量 protected int elementCount; /** * The amount by which the capacity of the vector is automatically * incremented when its size becomes greater than its capacity. If * the capacity increment is less than or equal to zero, the capacity * of the vector is doubled each time it needs to grow. * * @serial */
//当扩容的时候的增量 protected int capacityIncrement;

2.构造器

 public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
//创建一个数组对象,给予一定的大小
this.elementData = new Object[initialCapacity];
//给
capacityIncrement赋值

this.capacityIncrement = capacityIncrement;
    }

3.方法

add(E e):将指定元素添加到此向量的末尾

  
//注意此处添加了synchronized关键字,保证了线程安全
public synchronized boolean add(E e) {
//修改次数+1 modCount
++;
//保证容量大小够用 ensureCapacityHelper(elementCount
+ 1); 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 code
        int oldCapacity = elementData.length;
//如果capacityIncrement>0,这个值就是扩容的增量;否则扩容的增量大小等于现在的容量
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); }

remove(int index):移除指定位置的元素

    
//有synchronized关键字,保证线程安全
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)
//此处就是数组的复制操作,可以理解为把index+1开始的元素,长度为numMoved整体向前移动一个单位 System.arraycopy(elementData, index
+1, elementData, index, numMoved);
//将最后一个元素值设为null elementData[
--elementCount] = null; // Let gc do its work return oldValue; }

其它方法也是类似,这里就不再一一分析,主要是增加了synchronized关键字保证了线程安全,这是和ArrayList的最主要的区别。

原文地址:https://www.cnblogs.com/51life/p/9287365.html