Java集合框架-Collection-List-vector(遗留类)

发布于:2024-04-30 ⋅ 阅读:(31) ⋅ 点赞:(0)

一、vector层次结构图

在这里插入图片描述

二、概述

Vector类是单列集合List接口的一个实现类。与ArrayList类似,Vector也实现了一个可以动态修改的数组,两者最本质的区别在于——Vector类是支持线程同步的,因此它线程安全,支持多线程;而ArrayList是线程不同步的,线程不安全。Vector底层也是由一个Object类型的数组来实现的 (注意Vector维护的elementData数组没有用transient关键字修饰)

三、底层数据结构

/**
* The internal array used to hold members of a Vector. The elements are
* in positions 0 through elementCount - 1, and all remaining slots are null.
* @serial the elements
*/
protected T[] elementData;

/**
* The number of elements currently in the vector, also returned by
* {@link #size}.
* @serial the size
*/
protected int elementCount;

/**
* The amount the Vector's internal array should be increased in size when
* a new element is added that exceeds the current size of the array,
* or when {@link #ensureCapacity} is called. If <= 0, the vector just
* doubles in size.
* @serial the amount to grow the vector by
*/
protected int capacityIncrement;  

四、常用方法

略,和ArrayList很像
Java集合框架-Collection-List-ArrayList

五、和ArrayList的对比

同步:Vector 是同步的,也就是说它是线程安全的。每个单独的方法,如 add、get 等被 synchronized 关键字修饰,因此可以在多线程环境下使用而不会出现并发问题。 相比之下,ArrayList 不是线程安全的。
性能:由于 Vector 的方法是同步的,所以在单线程程序中它比 ArrayList 慢。但是,如果不需要线程安全且性能是重点考虑因素,ArrayList 通常是更好的选择。
增长策略:当 Vector 需要增长来存储更多元素时,它通常将其大小翻倍,而 ArrayList 则通常增长 50%。不过,这两个类都允许用户在创建时指定初始大小,并且可以通过调用 ensureCapacity 方法来控制数组的增长。