集合Collection(三):Vector源码解读.md

pre:List结构类图

image-20210408114632714

1.Vector

1.1.先总结

(1)为什么不推荐使用Vector

1.因为vector是线程安全的,所以效率低,这容易理解,类似StringBuffer
2.Vector空间满了之后,扩容是一倍,而ArrayList仅仅是一半
3.Vector分配内存的时候需要连续的存储空间,如果数据太多,容易分配内存失败
4.只能在尾部进行插入和删除操作,效率低

(2)Vector与ArrayList的区别?

  • Vector是同步,其方法都使用了synchronized关键字修饰

1.2.源码解读

概念:Vector类实现可增长的对象数组。 像数组一样,它包含可以使用整数索引访问的组件。 但是, Vector的大小可以根据需要增大或缩小,以适应创建Vector之后添加和删除项目的需要,它和ArrayList的行为及成员变量相似,迭代器也会抛出并发修改ConcurrentModificationException的异常,不同的是,Vector是同步的。如果不需要线程安全的实现,我们还是建议使用ArrayList

与新的集合实现不同, Vector是同步的。 如果不需要线程安全的实现,建议使用ArrayList代替Vector

1.2.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
     */
    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;

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -2767605614048989439L;

# java  JDK源码 

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×