Vector 简介:
Vector 和ArrayList一样都是实现了List接口。底层实现也是基于一个动态数组,每当我们添加元素时都会判断数组容量是否足够,如果不足则对数组进行扩容。这个数组默认长度为10,当然我们也可以设定数组的长度。每次扩容是默认是基于原有长度的2倍,Vector还允许设置每次扩容的长度。并且Vector 是线程安全的。
构造方法源码解析:
/**
* 创建指定长度,指定每次扩容的长度
*/
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 Vector(int initialCapacity) {
this(initialCapacity, 0);
}
/**
* 创建长度为10的空数组
*/
public Vector() {
this(10);
}
/**
* 创建带有初始值的数组
*/
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);
}
add()方法解析:
//方法前面加synchronized
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) {
// 获取数组长度
int oldCapacity = elementData.length;
//计算扩容长度(如果我们在构造函数中指定capacityIncrement值则每次扩容都是在原长度+capacityIncrement)否则就是加2倍
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);
}
你可以看到每次调用add(),都会进行判断数组是否已满,不满直接添加,如果满了则进行扩容。代码根据你是否设定capacityIncrement值,来决定扩容的长度。
get()方法源码解析:
//方法前面有synchronized
public synchronized E get(int index) {
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
get()方法很好理解: 判断index是否越界,是的话抛出异常,不是则返回数据
remove()方法源码解析:
//方法前面有synchronized
public synchronized E remove(int index) {
modCount++;
if (index >= elementCount)
throw new ArrayIndexOutOfBoundsException(index);
E oldValue = elementData(index);
int numMoved = elementCount - index - 1;
if (numMoved > 0)
//删除元素
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--elementCount] = null;
return oldValue;
}
Vector 和ArrayList区别:
1.Vector 是线程安全,它相关的方法都加上了synchronized同步锁。ArrayList则是非线程安全
2.Vector默认每次扩容是基于原来长度的2倍增长,并且每次扩容的长度可以在构造函数中指定,ArrayList默认是1.5倍,并且不能指定。