ArrayList源码分析

时间:2020-04-01 18:52:19   收藏:0   阅读:51

ArrayList日常用太多,写篇文章从记录下吧。

下面会从ArrayList里面的源码角度分析,在难点代码加上个人的理解。

下面的内容主要包含:ArrayList的属性、ArrayList的构造方法、ArrayList的crud方法。

 

public class ArrayList<E> extends AbstractList<E>  implements List<E>, RandomAccess, Cloneable, java.io.Serializable{   
private static final long serialVersionUID = 8683452581122892189L; /** * Default initial capacity.(默认容量大小) */ private static final int DEFAULT_CAPACITY = 10; /** * Shared empty array instance used for empty instances.(空的数组) */ private static final Object[] 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 = {}; /**    * (用于存放当前ArrayList数据的数组,transient代表不参与序列化) * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. */ transient Object[] elementData; // non-private to simplify nested class access /** * The size of the ArrayList (the number of elements it contains). *(当前ArrayList的元素个数) * @serial */ private int size; }
  /**
     * 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);
        }
    }

    /**
   * 构造一个初始容量为10的空列表(ArrayList的初始容量是10)
* Constructs an empty list with an initial capacity of ten. */ public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /**
   * 构造一个包含指定集合元素的列表,其顺序由集合的元素返回迭代器。 * 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; } }

  通过一个集合构造ArrayList的方法中,ArrayList通过Arrays.copyof()方法进行了数组元素复制。查看方法内部,最终是调用了System.arraycopy()方法。

  注意:System.arraycopy()用到的的浅拷贝,被复制的数组的元素,如果含有对象属性,该属性是不会被复制的,只会复制该对象属性的内存地址(引用传递)。

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        @SuppressWarnings("unchecked")
     //根据class的类型来决定是new 还是反射去构造一个泛型数组 T[] copy
= ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength);
     //利用native函数,批量赋值元素至新数组中。 System.arraycopy(original,
0, copy, 0, Math.min(original.length, newLength)); return copy; }

  1、add(E e)  

public boolean add(E e) {
     //确定数组容量是否足够
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
//确定数组容量是否足够(minCapacity:目前需要的数组容量)
private void ensureCapacityInternal(int minCapacity) {   ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
     //如果list的数组元素为空,则判断目前需要的数组容量是否大于默认的10,大于返回minCapacity,小于则返回默认的大小10
return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0)
  //如果需要的容量已经大于目前的数组长度,则进行扩容。这里和HashMap不一样,hashMap会有负载因子 grow(minCapacity); }
/** * The maximum size of array to allocate. * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit */
//最大数组大小需要保留一些header words,所以减去8. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; /**
* 对list进行扩容
* Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */ private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length;
  //新的容量为=旧的数组长度+旧的数组长度/2 (>>1为向右位移以为,即除以2)
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); }
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}

  2、remove

  (1) remove(int index) 删除一个具体位置的元素

     /**     
   * Removes the element at the specified position in this list.

   * Shifts any subsequent elements to the left (subtracts one from their * indices). * *
@param index the index of the element to be removed * @return the element that was removed from the list * @throws IndexOutOfBoundsException {@inheritDoc} */ public E remove(int index) {
     //判断数组越界,index不能大于等于数组长度 rangeCheck(index); modCount
++; E oldValue = elementData(index);      //删除操作第一步:把当前数组的index+1位置后的数组,复制到当前数组,从index位置开始。 int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved);
     //删除操作第二步:把数组最后的元素置null,GC掉 elementData[
--size] = null; // clear to let GC do its work return oldValue; }

  (2) remove(Object o) 列表中删除第一次出现的指定元素

  因为ArrayList底层是数组,允许元素重复。删除指定的元素是删除列表中第一个出现的

 /**
     * Removes the first occurrence of the specified element from this list,
     * if it is present.  If the list does not contain the element, it is
     * unchanged.  More formally, removes the element with the lowest index
     * <tt>i</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
     * (if such an element exists).  Returns <tt>true</tt> if this list
     * contained the specified element (or equivalently, if this list
     * changed as a result of the call).
     *
     * @param o element to be removed from this list, if present
     * @return <tt>true</tt> if this list contained the specified element
     */
    public boolean remove(Object o) {
        if (o == null) {
      //删除null元素
for (int index = 0; index < size; index++) if (elementData[index] == null) {
            //从0开始,第一个匹配的会被删除,删除完毕后return 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)
       //删除方式还是和第一个删除方法一样:把当前数组的index+1位置后的数组,复制到当前数组,从index位置开始。 System.arraycopy(elementData, index
+1, elementData, index, numMoved);
     //置空最后的元素 elementData[
--size] = null; // clear to let GC do its work }

  (3) removeAll(Collection<?> c)  删除一个集合的元素

public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
}

/** 
 * 批量移除 * complement(true:求交集,即RetainAll;false:求差集,即remove)
 *
*/
private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
        //遍历list
for (; r < size; r++) if (c.contains(elementData[r]) == complement)
            //目前是removeall,complement为false,则保留不在c集合里面的元素 elementData[w
++] = elementData[r]; } finally { // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws.
       //出现异常会导致 r !=size , 则将出现异常处后面的数据全部复制覆盖到数组里 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; }

 

 

    

 

原文:https://www.cnblogs.com/akid1994/p/12614507.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!