Vector的内部实现和ArrayList形式上一致,因此其实现原理可以参考ArrayList。
下面说说Vector和ArrayList的不同之处:
1.属性增加了capacityIncrement:
/**
* 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;
用于指定每次数组进行扩容的量,如果不指定或者指定为0,则每次按自身长度翻倍(2介绍)
2.扩容:
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
/**
* 这段方法是和ArrayList不同的一个地方
* ArrayList是扩容至size / 2
* Vectors是扩容capacityIncrement或者翻倍
* 如果在构造函数中指定了capacityIncrement,则扩容capacityIncrement
* 否则按原有的长度翻倍
*/
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
3.构造方法:
/**
* Constructs an empty vector with the specified initial capacity and
* capacity increment.
*
* @param initialCapacity the initial capacity of the vector
* @param capacityIncrement the amount by which the capacity is
* increased when the vector overflows
* @throws IllegalArgumentException if the specified initial capacity
* is negative
* ~和ArrayList的一个构造函数相似,初始化了elementData的长度,不同的地方是增加了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;
}
/**
* Constructs an empty vector with the specified initial capacity and
* with its capacity increment equal to zero.
*
* @param initialCapacity the initial capacity of the vector
* @throws IllegalArgumentException if the specified initial capacity
* is negative
* 和ArrayList的一个构造函数相似
*/
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);
}
/**
* Constructs a vector containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this
* vector
* @throws NullPointerException if the specified collection is null
* @since 1.2
*/
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);
}
4.Vector方法都有 synchronized修饰,因此是线程安全方法
~~~意义:
1.Vector是线程安全的,这是和ArrayList一个很大的区别。
2.Vector的扩容算法和ArrayList不一致,因此可以考虑好程序逻辑的前提下,适当地指定每次扩容的量和初始化数组的长度