Vector源码分析(对比ArrayList)

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

构造方法

其实二者在不少地方都是同样的,然而在构造方法上面, VectorArrayList多了一个方法:this

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的这个构造方法,不只可以指定初始化容量,还能指定当容量不够时,容量自增的大小。下面看扩容方法.code

扩容策略

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如出一辙。ci

同步

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

Enumeration

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

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不是,这一点很重要。get

相关文章
相关标签/搜索