Vector数据结构(jdk8)

看了下Vector的数据结构,简要记录下。

成员变量

    //放数据的
    protected Object[] elementData;
    //数据数量
    protected int elementCount;
    //要扩充的容量增长
    protected int capacityIncrement;
        

添加方法

    public synchronized boolean add(E e) {
        //操作数+1
        modCount++;
        //确认容量够不够
        ensureCapacityHelper(elementCount + 1);
        //赋值
        elementData[elementCount++] = e;
        return true;
    }

     private void ensureCapacityHelper(int minCapacity) {
        //溢出要扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    private void grow(int minCapacity) {
        //旧容量
        int oldCapacity = elementData.length;
        //扩容后的长度,默认是2倍,如果capacityIncrement不为空就以它为增量
        int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
                                         capacityIncrement : oldCapacity);
        //取max(newCapacity,minCapacity)为新容量
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //新容量溢出的处理
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        //复制数组
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    
    //返回 处理过溢出情况的minCapacity,
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

你可能感兴趣的:(Vector数据结构(jdk8))