从新认识java-Vector

源码解读

Vector的声明:java

public class Vector<E>
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable

经过继承和实现关系,能够看出Vector继承自抽象类AbstractList,实现了接口List, RandomAccess, Cloneable, java.io.Serializable.数组

功能和特色

  • Vector 继承了AbstractList,实现了List;因此,它是一个队列,支持相关的添加、删除、修改、遍历等功能。
  • Vector 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在Vector中,咱们便可以经过元素的序号快速获取元素对象;这就是快速随机访问。
  • Vector 实现了Cloneable接口,即实现clone()函数。它能被克隆。

与ArrayList的不一样点:Vector中的操做是线程安全的。安全

Vector的实现

常量

//list初始容量
private static final int DEFAULT_CAPACITY = 10;

变量

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

构造方法

public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}

public Vector(int initialCapacity) {
    this(initialCapacity, 0);
}

public Vector() {
    this(10);
}

public Vector(Collection<? extends E> c) {
    elementData = c.toArray();
    elementCount = elementData.length;
    // c.toArray might (incorrectly) not return Object[] (see 6260652)
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}

第一种方法须要一个默认的容量大小和每次容量增加的大小; 第二个是只设置初始容量的构造方法; 第三个是默认的构造方法,会默认建立一个容量为10的 Vector ; 第四个则传给一个 Collection ,注意,无论 Collection 里面是什么类型,最后放进 Vector 都会上转为 Object,与ArrayList相似。less

当capacityIncrement=0时,容量须要增加时,直接翻倍。 实现构造器调用,节省代码。值得借鉴。dom

核心方法

几乎全部的操做方法与ArrayList一致,只有数组容量的增加策略不一样: copyInto函数

public synchronized void copyInto(Object[] anArray) {
    System.arraycopy(elementData, 0, anArray, 0, elementCount);
}

为何是线程安全的?

数据操做方法都是用synchronized关键字修饰,因此是县城安全的。this

小结

  • 与ArrayList的区别:
  • 线程安全性:
  • 容量增加策略:
  • 与ArrayList联系:
    • 都是基于数组实现
    • 都是实现了AbstractList抽象类,List接口,Clone接口,RandomAccess接口和Serializable接口。

Thanks for reading! want more线程

相关文章
相关标签/搜索