【日拱一卒】ArrayList的add方法及扩容过程

2020-08-19  本文已影响0人  写代码的杰西

add方法

 public boolean add(E e) {
        //确认空间大小
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        //放入数组的末尾(数组有可能扩容过)
        elementData[size++] = e;
        return true;
    }

private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

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

        // overflow-conscious code 
//如果所需最小长度大于当前数组长度就扩容
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

扩容的grow方法

private void grow(int minCapacity) {
        // overflow-conscious code
         //旧数组长度
        int oldCapacity = elementData.length;
      //新数组长度为旧数组长度1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        //新数组长度仍小于所需长度,则用所需长度
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
      // 比int最大值-8 还大,就进入huge数组方法
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        //旧数组copy到新数组
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
上一篇下一篇

猜你喜欢

热点阅读