java之ArrayList.add

ArrayList添加
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
elementData[size++] = e :e为传入的需要存储的元素,elementData 是ArrayList中存放元素的数组缓存区,当ArrayList初始化时长度为0,当存放第一个元素时,长度为10
    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access
ensureCapacityInternal(size + 1) :size为ArrayList的长度,表示当前集合中的元素数量
  private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }
    private static int calculateCapacity(Object[] elementData, int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            return Math.max(DEFAULT_CAPACITY, minCapacity);
        }
        return minCapacity;
    }
minCapacity:表示最小容量,calculateCapacity()方法中逻辑:如果向集合中添加元素时elementData为长度为零的数组,则设置为初始容量为DEFAULT_CAPACITY=10
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
modCount:修改次数,判断使用最小容量减去当前数组的长度是否大于零,如果大于零则表示需要扩容,反之当前容量不需要扩容
  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);
    }

grow()为扩容方法,传入当前容量值,获取当前数组缓存区的长度,根据当前缓冲区长度进行计算扩容,扩容的数量是当前缓存区长度的1.5倍。最后使用Arrays.copyOf方法进行数组扩容



 
原文地址:https://www.cnblogs.com/shiguotao-com/p/10060330.html