ArrayList 源码理解

扩容机制:

源码如下:

minCapacity:最小需要的容量,也就是说存储数据的数组最小需要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;
    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);
}

一、先判断最小需要的长度是否大于原本数组的长度,如果大于,才需要扩容。

二、根据原本数组的长度扩容一半,代码如下:elementData是ArrayList中存储真实数据的数组

int oldCapacity = elementData.length;

int newCapacity = oldCapacity + (oldCapacity >> 1);

三、扩容后的新长度与最小需要的长度对比,取值比较大的那个。

四、判断要扩容的新长度是否会超过jvm对数组长度的限制(Integer.MAX_VALUE-8),如果大于Integer.MAX_VALUE-8,那就尝试创建Integer.MAX_VALUE长度的数组,此时在有些虚拟机上会溢出。

猜你喜欢

转载自blog.csdn.net/qq_36951116/article/details/84997716