ArrayList源码

源码分析

ArrayList

默认容量 DEFAULT_CAPACITY = 10; // 是添加元素之后的默认容量,如果没有添加任何元素,容量为0
存放元素的数组 elementData 添加元素
size 实际元素个数

  // 创建集合 size 0 容量 0 每次扩容会变成原来的1.5倍
  ArrayList arrayList = new ArrayList<>();

  add() // 添加元素
  // add()方法源码
  public boolean add(E e) {
    ensureCapacityInternal(size + 1);    // Increments modCount!!
    elementData[size++] = e;
    return true;
  }

  // ensureCapacityInternal
  private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
      minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    ensureExplicitCapacity(minCapacity);
  }

  // ensureExplicitCapacity
  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;
        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);
    }
posted @ 2022-06-11 02:12  zhiless  阅读(23)  评论(0编辑  收藏  举报