JDK1.8 ArrayList数组源码

序言

ArrayList底层通过数组实现。

ArrayList即动态数组,实现了动态的添加和减少元素。

需要注意的是,容量拓展,是创建一个新的数组,然后将旧数组上的数组copy到新数组,这是一个很大的消耗

所以在我们使用ArrayList时,最好能预计数据的大小,在第一次创建时就申请够内存。这就是许多博客说在第一次创建就申请够足够内存的原因。

    /**
     * Increases the capacity to ensure that it can hold at least the
     * number of elements specified by the minimum capacity argument.
     *
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
grow扩容函数

资料

https://blog.csdn.net/qq_26323323/article/details/86080902

https://blog.csdn.net/weixin_40374341/article/details/86492378

原文地址:https://www.cnblogs.com/cnki/p/10669677.html