ArrayList: how does the size increase?

后端 未结 19 853
既然无缘
既然无缘 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

    ArrayList does increases the size on load factor on following cases:

    • Initial Capacity: 10
    • Load Factor: 1 (i.e. when the list is full)
    • Growth Rate: current_size + current_size/2

    Context : JDK 7

    While adding an element into the ArrayList, the following public ensureCapacityInternal calls and the other private method calls happen internally to increase the size. This is what dynamically increase the size of ArrayList. while viewing the code you can understand the logic by naming conventions, because of this reason I am not adding explicit description

    public boolean add(E paramE) {
            ensureCapacityInternal(this.size + 1);
            this.elementData[(this.size++)] = paramE;
            return true;
        }
    
    private void ensureCapacityInternal(int paramInt) {
            if (this.elementData == EMPTY_ELEMENTDATA)
                paramInt = Math.max(10, paramInt);
            ensureExplicitCapacity(paramInt);
        }
    private void ensureExplicitCapacity(int paramInt) {
            this.modCount += 1;
            if (paramInt - this.elementData.length <= 0)
                return;
            grow(paramInt);
        }
    
    private void grow(int paramInt) {
        int i = this.elementData.length;
        int j = i + (i >> 1);
        if (j - paramInt < 0)
            j = paramInt;
        if (j - 2147483639 > 0)
            j = hugeCapacity(paramInt);
        this.elementData = Arrays.copyOf(this.elementData, j);
    }
    

提交回复
热议问题