JDK源码之Vector

Vector 是 JDK 基础容器,本质上就是对数组的操作集合
从其存储数据的数据结构即可看出
protected Object[] elementData

先来看看 Vector 几个参数

protected int elementCount; 数组当前元素个数
protected int capacityIncrement; 当数组容量不够时,扩容大小

Vector 的构造函数

public Vector(int initialCapacity, int capacityIncrement) {
    super();
    if (initialCapacity < 0)//如果初始容量小于0,抛出异常
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];//初始化数组
    this.capacityIncrement = capacityIncrement;
}

Vector 是线程安全的,但是其线程安全的实现是通过大量总线锁 synchronized 修饰,但是其外围函数都是 使用 实现的,所以其效率很低

public synchronized void copyInto(Object[] anArray)
public synchronized void trimToSize()
public synchronized void ensureCapacity(int minCapacity)
public synchronized void setSize(int newSize)
public synchronized int capacity()
public synchronized int size()
public synchronized boolean isEmpty()
public synchronized int indexOf(Object o, int index)
public synchronized int lastIndexOf(Object o)
public synchronized int lastIndexOf(Object o, int index)
public synchronized E elementAt(int index)
public synchronized E firstElement()
public synchronized E lastElement()
public synchronized void setElementAt(E obj, int index)
public synchronized void removeElementAt(int index)
public synchronized void addElement(E obj)
......

Vector 很简单,其扩容操作 grow 虽然没有使用 synchronized 修饰,但是其外围函数都是使用 synchronized 修饰的,所以仍然是线程安全的

private void grow(int minCapacity) {
    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 删除元素操作 removeElementAt

public synchronized void removeElementAt(int index) {
    modCount++;
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                                                 elementCount);
    }
    else if (index < 0) {
        throw new ArrayIndexOutOfBoundsException(index);
    }
    int j = elementCount - index - 1;
    if (j > 0) {
        System.arraycopy(elementData, index + 1, elementData, index, j);
    }
    elementCount--;
    elementData[elementCount] = null; /* to let gc do its work */ 这个比较好,删除元素,需要移动删除元素之后的所有的元素,空出最后一个位置,通过置最后一个位置为null,方便垃圾收集
}

猜你喜欢

转载自blog.51cto.com/superhakce/2117728