Vector源码个人解读
Vector类的基本属性
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; /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -2767605614048989439L;
其实跟ArrayList没有多少区别,底层也是一个elementData数组。
Vector构造器
public Vector(int initialCapacity) { this(initialCapacity, 0); } /** * Constructs an empty vector so that its internal data array * has size {@code 10} and its standard capacity increment is * zero. */ public Vector() { this(10); }
可以发现,如果是无参,那么默认长度就是10,有参的话就看参数的值。
与ArrayList的扩容机制不同,vector是按两倍扩容的
private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity);//这个三元运算符,其实就是两倍扩容。capacityIncrement是写死的,一直位为0. if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); elementData = Arrays.copyOf(elementData, newCapacity); }
其余方法与ArrayList大同小异。
总结:1.ArrayList扩容机制是默认为0,无参则为10,有参则之后需要扩容按照1.5倍进行扩容。Vector扩容机制是默认就是10,之后按2倍扩容
2.ArrayList是线程不安全的,而Vector的绝大多数方法都是有synchronization(同步)的使用,所以是线程安全的,因此性能也就比ArrayList差。
3.当作数据操作主要为索引或者只是在集合末端增加、删除元素时,两者效率都比较高。