Vector简介
构造方法
- public Vector()
- public Vector(int initialCapacity)
public Vector(int initialCapacity, int capacityIncrement)
重要属性
- protected Object[] elementData;//用于保存Vector数据的数组
- protected int elementCount;//Vector中数据个数
- protected int capacityIncrement;//Vector容器的增量
Vector源码分析
public synchronized boolean add(E e) {
modCount++;//fail-fast判断机制
ensureCapacityHelper(elementCount + 1);//确保Vector容量足够,跳转到下一个方法
elementData[elementCount++] = e;//对应位置复制
return true;//返回布尔类型
}
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);//如果增量大于0,扩容后的大小为原来容量与增量的和,否则扩容为原来容量的一倍
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
public synchronized E remove(int index) {
modCount++;//fail-fast
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; // Let gc do its work
return oldValue;
}
Vector遍历方式
- 迭代器遍历
Iterator<String> iterator = vect.iterator(); while (iterator.hasNext()){ iterator.next(); }
- forEach遍历
for (String s : vect) { }
- RandomAccess遍历
for (int i = 0;i<vect.size(); i++){ vect.get(i); }
- Enumeration遍历
Enumeration<String> elements = vect.elements(); while (elements.hasMoreElements()){ elements.nextElement(); }