序言

ArrayList底层通过数组实现。

JDK1.8 ArrayList数组源码

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

 

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

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

JDK1.8 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扩容函数

相关文章:

  • 2021-07-16
  • 2021-07-13
  • 2021-11-17
  • 2022-12-23
  • 2022-01-08
  • 2021-07-04
猜你喜欢
  • 2021-07-01
  • 2022-12-23
  • 2021-08-01
  • 2021-04-04
  • 2021-07-05
  • 2021-11-10
  • 2021-07-04
相关资源
相似解决方案