Vector源码分析(对比ArrayList)

629 查看

在上篇文章ArrayList源码浅析中分析了一下 ArrayList的源码和一些重要方法,现在对比 ArrayList,总结一下 VectorArrayList的不同

构造方法

其实两者在很多地方都是一样的,然而在构造方法上面, VectorArrayList多了一个方法:

public Vector(int initialCapacity, int capacityIncrement) {
        super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        this.elementData = new Object[initialCapacity];
        this.capacityIncrement = capacityIncrement;
    }

主要是因为 ArrayList中没有 capacityIncrement这个变量, vector的这个构造方法,不仅能够指定初始化容量,还能指定当容量不够时,容量自增的大小。下面看扩容方法.

扩容策略

ArrayList中,扩容的时候一般都是增加0.5倍左右,而在 Vector中,如果指定了这个 capacityIncrement,就会在原来容量的基础上增加 capacityIncrement;如果没有指定,则增加一倍容量。

private void grow(int minCapacity) {
        // overflow-conscious code
        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);
    }

除了这一点,其它和 ArrayList一模一样。

同步

众所周知, Vector是同步的而 ArrayList不是, Vector在一些必要的方法上都加了 synchronized关键字,但是这也会加大系统开销。

Enumeration

Vector中有一个 elements()方法用来返回一个 Enumeration,以匿名内部类的方式实现的:

 public Enumeration<E> elements() {
        return new Enumeration<E>() {
            int count = 0;

            public boolean hasMoreElements() {
                return count < elementCount;
            }

            public E nextElement() {
                synchronized (Vector.this) {
                    if (count < elementCount) {
                        return elementData(count++);
                    }
                }
                throw new NoSuchElementException("Vector Enumeration");
            }
        };
    }

Enumeration接口和 Iterator类似,都用作于对集合进行迭代,不过没有删除功能,已经被 Iterator取代。还有IteratorFast-Fail的,但 Enumeration不是,这一点很重要。