0%

阅读ArrayList源码

  • 创建

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    /*
    有参构造
    参数大于0,创建初始容量等于参数
    等于0,创建空
    */
    public ArrayList(int initialCapacity) {
    if (initialCapacity > 0) {
    this.elementData = new Object[initialCapacity];
    } else if (initialCapacity == 0) {
    this.elementData = EMPTY_ELEMENTDATA;
    } else {
    throw new IllegalArgumentException("Illegal Capacity: "+
    initialCapacity);
    }
    }

    /*
    无参构造
    创建空,这里常量空数组定义与有参空数组不同
    为了扩容时区分
    */
    public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /*
    参数是集合子类
    size不为0时,若传入集合本身就是ArrayList,直接指向
    否则,复制一遍
    */
    public ArrayList(Collection<? extends E> c) {
    Object[] a = c.toArray();
    if ((size = a.length) != 0) {
    if (c.getClass() == ArrayList.class) {
    elementData = a;
    } else {
    elementData = Arrays.copyOf(a, size, Object[].class);
    }
    } else {
    // replace with empty array.
    elementData = EMPTY_ELEMENTDATA;
    }
    }
  • /*
    将当前列表容量最小化,为了最小化存储
    */
    public void trimToSize() {
        modCount++;
        if (size < elementData.length) {
            elementData = (size == 0)
              ? EMPTY_ELEMENTDATA
              : Arrays.copyOf(elementData, size);
        }
    }
    
    /*
    将当前列表容量扩容到能包含指定参数的大小
    注意通过无参构造的“空”不会扩容,另外若需要大小小于等于10,也不会扩容
    */
    public void ensureCapacity(int minCapacity) {
            if (minCapacity > elementData.length
                && !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
                     && minCapacity <= DEFAULT_CAPACITY)) {
                modCount++;
                grow(minCapacity);
            }
        }
    
     private Object[] grow(int minCapacity) {
            return elementData = Arrays.copyOf(elementData,
                                               newCapacity(minCapacity));
        }
    
    /*
    重点
    新大小等于原来大小+原来大小的一半(向下取整)
    如果还不够,
    如果本来就是无参构造的空数组,扩容到10和新大小的最大值
    */
    private int newCapacity(int minCapacity) {
            // overflow-conscious code
            int oldCapacity = elementData.length;
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            if (newCapacity - minCapacity <= 0) {
                if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
                    return Math.max(DEFAULT_CAPACITY, minCapacity);
                if (minCapacity < 0) // overflow
                    throw new OutOfMemoryError();
                return minCapacity;
            }
            return (newCapacity - MAX_ARRAY_SIZE <= 0)
                ? newCapacity
                : hugeCapacity(minCapacity);
        }
    
------ THEEND ------

欢迎关注我的其它发布渠道