Vector和ArrayList集合都实现了List接口,底层实现都是基于数组的。一般实际项目使用场景主要是ArrayList的天下,但不可说Vector一无是处,没任何用武之地。Vector被synchronized修饰是线程安全的。它们主要区别亦是线程安全和非线程安全,低效率和高效率;以及扩容的策略不一样。1.8版jdk中ArrayList默认容量为0,第一次扩容为10,之后扩容都是1.5倍。Vector是比较老古董的一个集合,官方也几乎没怎么优化它,相比使用它还有更好的选择,这里不一 一赘述,Vector的默认容量为10,之后依次扩容为基础的2倍。
Vector集合的特定
Vector也实现了List接口,和ArrayList用法基本相同。
Vector和ArrayList一样,底层也是一个Object类型的数组Object[]。
ArrayList的无参构造默认数组容量是10,Vector的默认容量也是10。
Vector和ArrayList构建时一样,都可以指定容量的大小。
当集合容量不够用时,Vector和ArrayList一样,都会实现自动扩容。
ArrayList集合的自动扩容的新容量是原来的1.5倍。
Vector集合的自动扩容的新容量是原来的2倍。
Vector是线程安全的,方法有使用sychronized修饰符修饰。ArrayList是非线程安全的。
实例代码
public class VectorTest {
public static void main(String[] args) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
/**
-----------------------------------------------------------------
结果
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
*/
总结
Vector内部结构是数组,与Collections.synchronizedList(new ArrayList())类似。
Vector可以指定扩容大小,默认是扩容到原数组长度的 2 倍;ArrayList不能指定扩容大小,直接扩容到原数组大小的 1.5 倍。
SynchronizedList是一个包装类,可以将List子类都包装为同步队列,从非线程安全队列转为线程安全队列,没有性能延迟,直接包装即可;Vector是一个基于数组的同步队列,其他队列想要转换为Vector,需要有数据拷贝。
SynchronizedList的迭代器没有做同步,需要用户自己实现;Vector的迭代器做好了同步,开发人员不需要关心同步。
Vector至今未标记Deprecated,而且随着 JDK 发布,也在更新实现。虽然 JDK 承诺兼容,但是一直没有标记过期,其用意不得而知。