ArrayList源码解析

ArrayList是List集合的一个实现类,它可以快速查询元素。ArrayList的查找时通过索引下标进行查找,所以ArrayList的查找快,当从ArrayList的中间位置插入或者删除元素时,需要对数组进行复制、移动、代价比较高。因此,它适合随机查找和遍历,不适合插入和删除。ArrayList线程不安全。

/**
 * Default initial capacity.
 */
private static final int DEFAULT_CAPACITY = 10;
//当构建一个无参构造器时,ArrayList会默认构造一个长度为10且空的数组。
/**
 * Default initial capacity.
 */
private static final int DEFAULT_CAPACITY = 10;
/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
/**
 * Shared empty array instance used for default sized empty instances. We
 * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
 * first element is added.
 */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};



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

private void ensureCapacityInternal(int minCapacity) {
// elementData和DEFAULTCAPACITY_EMPTY_ELEMENTDATA默认为空数组
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
// DEFAULT_CAPACITY和 minCapacity做比较,把大的数字赋值给minCapacity,由于是第一次添加元素所以返回默认的容量大小,它为10
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

private void ensureExplicitCapacity(int minCapacity) {
    modCount++;//当前对象操作次数
    // overflow-conscious code
    if (minCapacity - elementData.length > 0)//当前元素长度为零
        grow(minCapacity);//扩容
}

private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;//将当前元素长度赋值给oldCapacity
    int newCapacity = oldCapacity + (oldCapacity >> 1);// newCapacity的值是oldCapacity的1.5倍
    if (newCapacity - minCapacity < 0)//第一次添加元素newCapacity为0
        newCapacity = minCapacity;// newCapacity为10
// private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    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);//给元素进行扩容,如果是第一次添加元素需要将elementData的容量扩容到10,才能进行添加元素
}

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

 

上一篇:Stack的底层Vector源码浅析


下一篇:ArrayList的自动扩容机制