public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
//外部操作数
protected transient int modCount = 0;
}
public class Vector<E> extends AbstractList<E> implements List<E>{
//元素容器
protected Object[] elementData;//new Object[10]{null,null,null,null,...}
//元素个数
protected int elementCount;
//容量增量
protected int capacityIncrement;//0
public Vector() {
this(10);
}
//initialCapacity - 10
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
//initialCapacity - 10
//capacityIncrement - 0
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 synchronized boolean add(E e) {//线程安全的
modCount++;
ensureCapacityHelper(elementCount + 1);//扩容
elementData[elementCount++] = e;
return true;
}
private void ensureCapacityHelper(int minCapacity) {
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// oldCapacity - 10
int oldCapacity = elementData.length;
//newCapacity - 10 + 10
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<String> v = new Vector<>();
v.add("张三");
v.add("李四");
v.add("王五");
标签:capacityIncrement,Vector,int,minCapacity,elementData,initialCapacity,源码,底层 From: https://blog.51cto.com/u_16154651/6530559
- Vector底层数据结构是什么?
Object类型的一维数组- Vector的默认初始化容量是多少?
10- Vector的扩容机制是什么?
如果容量增量小于等于0,扩容机制是数组原来长度的两倍
如果容量增量大于0,扩容机制是数组原来长度+容量增量- Vector的特点是什么?
Vector是线程安全的集合