- Vector的基本介绍
- 源码剖析
- 使用无参构造器创建Vector对象,跟踪源码
- 使用有参构造器创建Vector对象,跟踪源码【待写】
- Vector底层结构和ArrayList的比较
-
Vector类的定义说明
-
Vector底层也是一个对象数组,
protected Object[] elementData;
-
Vector是线程同步的,即线程安全,Vector类的操作方法带有synchronized
public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); }
public class Vector_ {
public static void main(String[] args) {
Vector vector = new Vector();
for (int i = 0; i < 10; i++) {
vector.add(i);
}
vector.add(100);
vector.add(200);
}
}
装箱操作
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
执行vector.add
(1)modCount++:记录集合被修改的次数
(2)先确定是否需要扩容
(3)然后再执行赋值
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
如果elementData的大小不够,就调用grow()去扩容
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
真正的扩容
(1)使用扩容机制来确定要扩容到多大
(2)capacityIncrement=0,第一次oldCapacity=10,newCapacity=oldCapacity*2=20,即相当于按照2倍扩容
(3)扩容使用的是Arrays.copyOf()
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
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);
}
使用有参构造器创建Vector对象,跟踪源码【待写】
Vector底层结构和ArrayList的比较
| 底层结构 | 版本 | 线程 安全(同步)效率 | 扩容倍数 | |
|---|---|---|---|---|
| ArrayList | 可变数组 | jdk1.2 | 不安全,效率高 | 如果 有参构造1.5倍 如果是无参 1. 第一次10 2. 第二次开始按1.5扩 |
| Vector | 可变数组 Object[] | jdk1.0 | 安全,效率低 | 如果指定大小,则每次直接按2倍扩 如果是无参构造,默认10,满了 之后,按2倍扩容 |



