ArrayList: how does the size increase?

后端 未结 19 858
既然无缘
既然无缘 2020-11-29 18:11

I have a basic question on Java ArrayList.

When ArrayList is declared and initialized using the default constructor, memory space for 10 el

19条回答
  •  旧时难觅i
    2020-11-29 18:50

    Sun's JDK6:

    I believe that it grows to 15 elements. Not coding it out, but looking at the grow() code in the jdk.

    int newCapacity then = 10 + (10 >> 1) = 15.

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

    From the Javadoc, it says this is from Java 2 and on, so its a safe bet in the Sun JDK.

    EDIT : for those who didn't get what's the connection between multiplying factor 1.5 and int newCapacity = oldCapacity + (oldCapacity >> 1);

    >> is right shift operator which reduces a number to its half. Thus,
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    => int newCapacity = oldCapacity + 0.5*oldCapacity;
    => int newCapacity = 1.5*oldCapacity ;

提交回复
热议问题