ArrayList

作者: smallAttr | 来源:发表于2018-03-05 17:17 被阅读0次

说到ArrayList,底层基于Object[]数组实现的,详细的我不多说,随随便便一搜就是一大堆。最近也在看源码,结合自己的实际情况,不得不深研下它的动态扩容机制:

/**
     * 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);
    }
  1. 在现有数据容量上,扩容原来的1.5倍,至于为什么会选择扩容1.5倍呢?(发现 1.5 倍的扩容是最好的倍数。因为一次性扩容太大(例如 2.5 倍)可能会浪费更多的内存(1.5 倍最多浪费 33%,而 2.5 倍最多会浪费 60%,3.5 倍则会浪费 71%……)。但是一次性扩容太小,需要多次对数组重新分配内存,对性能消耗比较严重。所以 1.5 倍刚刚好,既能满足性能需求,也不会造成很大的内存消耗)。

  2. 扩容后如果还小于minCapacity。直接扩容为minCapacity。

  3. 再判断是否大于MAX_ARRAY_SIZE(为什么会减去8呢?一些虚拟机存在一些保留字),是就扩容为Integer.MAX_VALUE,否则就是MAX_ARRAY_SIZE。

/**
     * The maximum size of array to allocate.
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
    }

这里我们可以对比着hashMap的扩容机制,我觉得这篇文章(http://www.importnew.com/20386.html)写得非常详细,同时就hashMap的发行版本做了对比分析和测试。尤其在1.8版本中,很多细节优化。

相关文章

网友评论

      本文标题:ArrayList

      本文链接:https://www.haomeiwen.com/subject/tmihfftx.html