ArrayList有容量上限吗?

今天面试遇到这个问题:

首先先new一个

List<Integer> list =new ArrayList<Integer>();

调用无参构造函数默认初始容量为10,可以看到list.size()其底层如下:

/**
     * Returns the number of elements in this list.
     *
     * @return the number of elements in this list
     */
    public int size() {
        return size;
    }

在这段源码里我们可以发现,返回的是一个int类型,

那么可以说明ArrayList是有最大容量的,最大为Integer.MAX_VALUE,即((2^31)-1)2147483647

到这里就结束了?别急。

再查看另外一段代码:

 /**
     * 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;

这段源码告诉了我们,有些虚拟机在阵列中保留一些头信息,防止内存溢出,

此时,我们发现ArrayList最大容量是(Integer.MAX_VALUE-8)

问题来了,为啥是减去8而不是减去其他数字呢

请看链接

ArrayList是存储在内存里的,存储的最大容量也取决于运行Java代码的平台内存和JVM的堆比例

按照本例,存储的是Integer对象,那么计算下内存:((2^31)-1)*32bits=68719476704 bits,大约是8G

如果超出堆比例,则会报错:OutOfMemoryError 内存溢出

****************************************************************************************************************************

如果我定义了一个初始容量为10的ArrayList,我再增加一个元素,此时容量为11,是否会报错?

当然不会了,ArrayList会进行比较,如果比原来的容量要大,则会进行扩容

新容量=旧容量*1.5

来看看底层是如何实现扩容的

/**
         * 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); //新容量扩大到原来的1.5倍,右移一位相当于原来的值除以2
            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);
        }


猜你喜欢

转载自blog.csdn.net/chineseyoung/article/details/80786067