Vector

来源:互联网 发布:涡扇15和f119数据对比 编辑:程序博客网 时间:2024/05/22 17:53

Vector

jdk 1.7 API: http://tool.oschina.net/apidocs/apidoc?api=jdk_7u4

a growable array of objects, the size of a Vector can grow or shrink

Vector与ArrayList的主要区别,为什要用Vector

Vector的方法都是同步的(Synchronized),是线程安全的(thread-safe)

两个重要的参数capacitycapacityIncrement

capacity

vector的容量,一定大于等于size

public synchronized int capacity(){    return elementData.length;//Object[] elementData存放vector元素}

capacityIncrement

capacity每次增长的数量,当size要大于capacity时,就会增长capacityIncrement

vector构造函数,默认构造函数构造一个capacity为10,capacityIncrement为0的vector

public Vector(int paramInt1, int paramInt2){    if (paramInt1 < 0) {        throw new IllegalArgumentException("Illegal Capacity: " + paramInt1);    }    elementData = new Object[paramInt1];    capacityIncrement = paramInt2;}public Vector(int paramInt){    this(paramInt, 0);}public Vector(){    this(10);}

添加元素方法addElement(E obj)与add(E e)有什么差别么

并没有!源码实现相同,唯一不同的是add()方法有boolean返回值。
为什么会出现这种情况?因为Vector是在JDK 1.2之后将Vector改为List接口的实现,比如addElement(E obj)就是之前遗留的方法。

Vector已经过时了,不推荐使用

官网的说明,大致意思是若需要线程安全使用Vector会比调用Collections.synchronizedList方法的ArrayList速度稍快,只是稍快,而且提醒一定要使用List的接口操作Vector,否则可能会有问题。

If you need synchronization, a Vector will be slightly faster than an ArrayList synchronized with Collections.synchronizedList. But Vector has loads of legacy operations, so be careful to always manipulate the Vector with the List interface or else you won’t be able to replace the implementation at a later time.

0 0