基于java1.8 ArrayList 源码分析

1、结构

  • ArrayList 继承 AbstractList 抽象类,该类是只支持按次序访问
  • ArrayList 实现了 List 接口
  • 实现了RandomAccess接口,表明ArrayList支持快速(通常是固定时间)随机访问
  • 实现了 Cloneable 接口,覆盖了 clone 方法,即可以被克隆
  • 实现了 Serializable 接口,支持序列化
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

2、内部变量

// 默认容量为10
private static final int DEFAULT_CAPACITY = 10;

// 空对象数组
private static final Object[] EMPTY_ELEMENTDATA = {};

// 默认空对象数组,由空的构造参数生成
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

// ArrayList对象实际上就是一个容器数组
transient Object[] elementData; // non-private to simplify nested class access

// 实际元素大小
private int size;

// 最大容量
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

3、构造函数

/**
 * Constructs an empty list with an initial capacity of ten.
 * 无参构造
 */
public ArrayList() {
    this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}

/**
 * Constructs an empty list with the specified initial capacity.
 *
 * @param  initialCapacity  the initial capacity of the list
 * @throws IllegalArgumentException if the specified initial capacity is negative
 *
 * 指定容量大小的构造函数
 */
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);
    }
} 

/**
 * Constructs a list containing the elements of the specified
 * collection, in the order they are returned by the collection's iterator.
 * @param c the collection whose elements are to be placed into this list
 * @throws NullPointerException if the specified collection is null
 *
 * 由另一个集合创建的构造函数
 */
public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    if ((size = elementData.length) != 0) {
        // c.toArray might (incorrectly) not return Object[] (see 6260652)
        if (elementData.getClass() != Object[].class)
            elementData = Arrays.copyOf(elementData, size, Object[].class);
    } else {
        // replace with empty array.
        this.elementData = EMPTY_ELEMENTDATA;
    }
}

4、主要方法{get()、set()、add()、remove()、clear()、contains()}

4.1 get()

public E get(int index) {
    // 防止越界,索引不能大于数组长度
    rangeCheck(index);
    
    // 直接返回索引处的元素
    return elementData(index);
}

4.2 set()

/**
 * Replaces the element at the specified position in this list with the specified element.
 *
 * @param index index of the element to replace
 * @param element element to be stored at the specified position
 * @return the element previously at the specified position
 * @throws IndexOutOfBoundsException {@inheritDoc}
 *
 * 用指定的元素替换列表中指定位置的元素
 */
public E set(int index, E element) {
    rangeCheck(index);

    E oldValue = elementData(index);
    elementData[index] = element;
    return oldValue;
}

4.3 add()

add(E e)

  1. ensureCapacityInternal(size+1)方法,在该方法中首先判断了当前数组是否是空数组,如果是则比较加入的个数与默认个数(10)比较,取较大值,否则调用2方法。
  2. ensureExplicitCapacity(int minCapacity)方法,在该方法中首先是对modCount+1,判断数组真实元素个数加1后的长度与当前数组长度大小关系,如果小于0,返回,如果大于0,则调用3方法。
  3. grow(minCapacity)方法,使用 oldCapacity + (oldCapacity >> 1)是当前数组的长度变为原来的1.5倍,再与扩容后的长度以及扩容的上限值进行对比,然后调用4方法。
  4. Arrays.copyOf(elementData, newCapacity)方法,该方法的底层就是调用System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength))方法,把旧数据的数据拷贝到扩容后的新数组里面,返回新数组,然后再把新添加的元素赋值给扩容后的size+1的位置里面。

add(int idnex,E element)

       主要的差异是增加了一行代码:System.arraycopy(elementData, index, elementData, index + 1, size - index),从index位置开始以及之后的数据,整体拷贝到index+1开始的位置,然后再把新加入的数据放在index这个位置,而之前的数据不需要移动。(这些动作比较消耗性能)

/**
 * add()
 * 在list末尾追加一个元素
 */
public boolean add(E e) {
	// 容量检测以及扩容
   ensureCapacityInternal(size + 1);  // Increments modCount!!
   // 将新元素增加到末尾
   elementData[size++] = e;
   return true;
}

private void ensureCapacityInternal(int minCapacity) {
	// 如果数组容器为空,初始化容器的容量,默认为10
   if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
       minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
   }
   
   ensureExplicitCapacity(minCapacity);
}

/**
* 确保数组长度大于等于最小容量
*/
private void ensureExplicitCapacity(int minCapacity) {
    modCount++;

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

/**
 * 扩容:容量在当前的基础上 + 50%
 */	
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    // 通过位运算符扩容,容量在当前的基础上 + 50%
    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);
}

// 指定索引add                                
public void add(int index, E element) {
    // 确保该索引要合法即大于等于0并且小于等于数组长度
    rangeCheckForAdd(index);

    // 确保数组容量大于等于size+1
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    // 将index索引位置(包括)及之后的元素都向后挪动一位
    System.arraycopy(elementData, index, elementData, index + 1,
                     size - index);
    // 将index索引处设置为新增元素
    elementData[index] = element;
    size++;
}

4.4 remove()

  1. rangeCheck(index) 进行越界检查
  2. modCount 记录修改次数(可以用来检测快速失败的一种标志。)
  3. 通过索引找到要删除的元素
  4. 计算要移动的位数
  5. 移动元素(其实是覆盖掉要删除的元素)
  6. 将–size上的位置赋值为null,让gc(垃圾回收机制)更快的回收它。
  7. 返回被删除的元素
/**
 * 根据索引移除对象
 */
public E remove(int index) {
    // 防止越界,索引不能大于数组长度
    rangeCheck(index);

    // 操作数+1
    modCount++;
    E oldValue = elementData(index);

    // 将index后的元素都向前挪动一位,原index的元素就删除了
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index, numMoved);
    // 数组长度减1
    elementData[--size] = null; // clear to let GC do its work

    return oldValue;
}

/**
 * remove 指定对象 Object o
 * 判断 o 是否为 null,为 null 则遍历移除集合中为 null 的对象
 * 不为 null 则移除指定对象
 */
public boolean remove(Object o) {
    if (o == null) {
        for (int index = 0; index < size; index++)
            if (elementData[index] == null) {
                fastRemove(index);
                return true;
            }
    } else {
        for (int index = 0; index < size; index++)
            if (o.equals(elementData[index])) {
                fastRemove(index);
                return true;
            }
    }
    return false;
} 

/*
 * Private remove method that skips bounds checking and does not
 * return the value removed.
 */
private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index+1, elementData, index, numMoved);
    elementData[--size] = null; // clear to let GC do its work
}

/**
 * 删除fromIndex到toIndex之间的全部元素,把toIndex以后的元素移动(size-toIndex)位,把左移后空 
 * 的元素置为null好让垃圾回收机制回收内存,最后把新数组的大小赋值给size
 *
 */
protected void removeRange(int fromIndex, int toIndex) {
    modCount++;
    int numMoved = size - toIndex;
    System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);

    // clear to let GC do its work
    int newSize = size - (toIndex-fromIndex);
    for (int i = newSize; i < size; i++) {
        elementData[i] = null;
    }
    size = newSize;
}

public boolean removeAll(Collection<?> c) {
    //非空检查
    Objects.requireNonNull(c);
    //删除指定集合中的所有元素
    return batchRemove(c, false);
}

private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
        for (; r < size; r++)
            if (c.contains(elementData[r]) == complement)
                elementData[w++] = elementData[r];
    } finally {
        // Preserve behavioral compatibility with AbstractCollection,
        // even if c.contains() throws.
        if (r != size) {
            System.arraycopy(elementData, r,
                             elementData, w,
                             size - r);
            w += size - r;
        }
        if (w != size) {
            // clear to let GC do its work
            for (int i = w; i < size; i++)
                elementData[i] = null;
            modCount += size - w;
            size = w;
            modified = true;
        }
    }
    return modified;
}	

4.5 clear()

/**
 * Removes all of the elements from this list.  The list will
 * be empty after this call returns.
 */
public void clear() {
    modCount++;

    // clear to let GC do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

4.6 contains()

/**
 * Returns <tt>true</tt> if this list contains the specified element.
 * More formally, returns <tt>true</tt> if and only if this list contains
 * at least one element <tt>e</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
 *
 * @param o element whose presence in this list is to be tested
 * @return <tt>true</tt> if this list contains the specified element
 */
public boolean contains(Object o) {
    return indexOf(o) >= 0;
}

/**
 * Returns the index of the first occurrence of the specified element
 * in this list, or -1 if this list does not contain the element.
 * More formally, returns the lowest index <tt>i</tt> such that
 * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
 * or -1 if there is no such index.
 */
public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

4.7 遍历

Iterator<String> it = arrayList.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
}

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    public void forEachRemaining(Consumer<? super E> consumer) {
        Objects.requireNonNull(consumer);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i >= size) {
            return;
        }
        final Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length) {
            throw new ConcurrentModificationException();
        }
        while (i != size && modCount == expectedModCount) {
            consumer.accept((E) elementData[i++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

总结:

  1. arrayList可以存放null。
  2. arrayList本质上就是一个elementData数组。
  3. arrayList区别于数组的地方在于能够自动扩展大小,其中关键的方法就是gorw()方法。
  4. arrayList中removeAll(collection c)和clear()的区别就是removeAll可以删除批量指定的元素,而clear是全是删除集合中的元素。
  5. arrayList由于本质是数组,所以它在数据的查询方面会很快,而在插入删除这些方面,性能下降很多,有移动很多数据才能达到应有的效果。
  6. arrayList实现了RandomAccess,所以在遍历它的时候推荐使用for循环。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值