ArrayList结构分析(jdk8)

ArrayList源码分析,基本和Vector一致,去掉了synchronized

    public boolean add(E e) {
        //初始化,扩容
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //赋值
        elementData[size++] = e;
        return true;
    }

    private void ensureCapacityInternal(int minCapacity) {
        //扩容(计算最小扩容容量)
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
    
    //计算扩容后的容量
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
    //增加操作数,忽略溢出操作
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    //扩容
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        //1.5倍旧容量
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //不小于最小容量
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        //超过最大容量就取最大
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        //数组复制
        elementData = Arrays.copyOf(elementData, newCapacity);
    }

posted @ 2019-10-25 13:20  六月过半  阅读(151)  评论(0编辑  收藏  举报