一 属性

  1. //初始容量
  2. private static final int DEFAULT_CAPACITY = 10;
  3. //指定arrayList容量为0的时候返回这个数组
  4. private static final Object[] EMPTY_ELEMENTDATA = {};
  5. //构造无参的对象的时候,返回这个
  6. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  7. //存放元素,第一次添加元素的时候扩容到 初始容量10
  8. transient Object[] elementData; // non-private to simplify nested class access
  9. private int size;

二 重要方法

  • Arrays.copyOf(elementData, size)
    • 底层的数组拷贝
  • ensureCapacity(int minCapacity)
    • 扩容方法(每次扩容原来容量的1.5倍)
  • System.arraycopy(elementData, 0, a, 0, size);
    • 底层数组的拷贝 本地方法
  • trimToSize

    • 将数组缩容为实际的容量,数组每次扩容会增加 newCapacity = oldCapacity + (oldCapacity >> 1)
    • 计算后也就是扩容1.5倍的大小

      三 添加

      1. public boolean add(E e) {
      2. ensureCapacityInternal(size + 1); // Increments modCount!!
      3. elementData[size++] = e;
      4. return true;
      5. }

      四 获取

      1. public E get(int index) {
      2. rangeCheck(index);
      3. return elementData(index);
      4. }

      五 删除

      1. public E remove(int index) {
      2. rangeCheck(index);
      3. modCount++;
      4. E oldValue = elementData(index);
      5. int numMoved = size - index - 1;
      6. if (numMoved > 0)
      7. System.arraycopy(elementData, index+1, elementData, index,
      8. numMoved);
      9. //最后一位gc回收
      10. elementData[--size] = null; // clear to let GC do its work
      11. return oldValue;
      12. }

      六 扩容

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

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

      // overflow-conscious code if (minCapacity - elementData.length > 0)

      1. grow(minCapacity);

      }

  1. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  2. private void grow(int minCapacity) {
  3. // overflow-conscious code
  4. int oldCapacity = elementData.length;
  5. //扩容大小为原来长度的1.5倍
  6. int newCapacity = oldCapacity + (oldCapacity >> 1);
  7. if (newCapacity - minCapacity < 0)
  8. newCapacity = minCapacity;
  9. if (newCapacity - MAX_ARRAY_SIZE > 0)
  10. newCapacity = hugeCapacity(minCapacity);
  11. // minCapacity is usually close to size, so this is a win:
  12. elementData = Arrays.copyOf(elementData, newCapacity);
  13. }
  14. private static int hugeCapacity(int minCapacity) {
  15. if (minCapacity < 0) // overflow
  16. throw new OutOfMemoryError();
  17. return (minCapacity > MAX_ARRAY_SIZE) ?
  18. Integer.MAX_VALUE :
  19. MAX_ARRAY_SIZE;
  20. }

```