Vector和Stack详解

446 阅读1分钟

Vector

Vector可以说成是ArrayList的线程安全版本,都是通过动态数组实现,Vector是通过给实例对象加锁实现线程安全。VectorArrayList的另一个区别在于Vector的扩容可以指定每次扩容的大小,没指定的话扩容为原来的2倍。

protected int capacityIncrement;

private int newCapacity(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                     capacityIncrement : oldCapacity);
    if (newCapacity - minCapacity <= 0) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return minCapacity;
    }
    return (newCapacity - MAX_ARRAY_SIZE <= 0)
        ? newCapacity
        : hugeCapacity(minCapacity);
}

Stack

Stack继承Vector,它也是线程安全的,元素按照先进后出的顺序被访问,它提供了以下方法:

public Stack() {
}

/**
 * 入栈
 */
public E push(E item) {
    addElement(item);

    return item;
}

/**
 * 出栈
 */
public synchronized E pop() {
    E       obj;
    int     len = size();

    obj = peek();
    removeElementAt(len - 1);

    return obj;
}

/**
 * 访问栈顶元素
 */
public synchronized E peek() {
    int     len = size();

    if (len == 0)
        throw new EmptyStackException();
    return elementAt(len - 1);
}

/**
 * 判断栈是否为空
 */
public boolean empty() {
    return size() == 0;
}

可以看到,当栈为空,如果访问栈顶元素或者进行出栈操作,会抛出EmptyStackException异常。