首页 > 其他 > 详细

Vector数据结构(jdk8)

时间:2019-10-25 11:28:07      阅读:89      评论:0      收藏:0      [点我收藏+]

看了下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)

原文:https://www.cnblogs.com/june777/p/11731974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!