ArrayList: how does the size increase?

后端 未结 19 862
既然无缘
既然无缘 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条回答
  •  感情败类
    2020-11-29 18:26

    Context java 8

    I give my answer here in the context of Oracle java 8 implementation, since after reading all the answers, I found that an answer in the context of java 6 has given by gmgmiller, and another answer has been given in the context of java 7. But how java 8 implementes the size increasement has not been given.

    In java 8, the size increasement behavior is the same as java 6, see the grow method of ArrayList:

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

    the key code is this line:

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

    So clearly, the growth factor is also 1.5, the same as java 6.

提交回复
热议问题