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
.数组
与ArrayList的不一样点: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
Thanks for reading! want more线程