Java中ArrayList的扩容

Java中的容器ArrayList的扩容是按1.5倍进行的,以ArrayList的add()方法为例分析一下其内部实现。

add()方法的源码如下:

    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

可以看到,每次增加元素时都要确保ArrayList的容量要足够使用:如果容量足够,则下标加一,将元素加入(其底层elementData是一个数组);如果容量不够,则需要进行扩容。具体实现在方法ensureCapacityInternal()中:

    private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

首先是刚开始时,数组默认为空,然后创建默认长度DEFAULT_CAPACITY为10的数组。当要新加入一个元素时,传入参数minCapacity(实际元素个数+1)作为判断依据,比较对象为elementData.length(数组的长度,并不一定等于实际元素个数),如果容量不够,则进行扩容,即grow()方法:

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

在进行扩容时,通常情况下:新容量=旧容量+旧容量/2(取整),旧容量是指当前的数组长度而不是实际元素个数,即可实现1.5倍扩容。当然如果容量超过了MAX_ARRAY_SIZE(虚拟机限制),那新容量就等于 231-1,此时可能会产生OutOfMemoryError错误。当确定了新容量后,就需要进行数组拷贝扩容Arrays.copyOf():

    @SuppressWarnings("unchecked")
    public static <T> T[] copyOf(T[] original, int newLength) {
        return (T[]) copyOf(original, newLength, original.getClass());
    }

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

简单地说就是创建新容量大小的新数组,将原数组的数据拷贝过去。具体的拷贝操作System.arraycopy()则是本地方法(外部语言)实现的,无法看到源码:

    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值