本次博客带领大家学习集合中的Vector底层结构和源码分析。
Vector的基本介绍
- Vector类的定义说明
- Vector底层也是一个对象数组,protected Object[] elementData;
- Vector 是线程同步的,即线程安全,Vector类的操作方法带有synchronized。
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
- 在开发中,需要线程同步安全时,考虑使用Vector。
Vector和ArrayList的比较
底层结构 | 版本 | 线程安全(同步)效率 | 扩容倍数 | |
---|---|---|---|---|
ArrayList | 可变数组 | jdk1.2 | 不安全,效率高 | 如果有参构造1.5倍;如果是无参,第一次扩容10,第二次开始按1.5倍扩 |
Vector | 可变数组 | jdk1.0 | 安全,效率不高 | 如果有参构造2倍,如果是无参,第一次扩容10,第二次开始按2倍扩 |
Vector 扩容源码分析
- new Vector() 底层,其实就是直接传入10给有参构造器。
public Vector() {
this(10);
}
- 下面这个方法就添加数据到vector集合。
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
- 确定是否需要扩容 条件 :minCapacity - elementData.length > 0。
private void ensureCapacityHelper(int minCapacity) {
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
- 如果需要的数组大小不够用,就需要扩容。
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);
}
inCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}