深入理解ArrayList源码解析

package com.test.effectiveJava;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.RandomAccess;

/**
 * ArrayList  源码解析
 * @author 
 * 2017年12月5日
 * @param <E>
 */
public class ArrayList<E> extends AbstractList<E>  implements List<E>, RandomAccess, Cloneable, java.io.Serializable{

	private static final long serialVersionUID = -4053510823272315648L;

	 /**
     * 默认初始容量  
     * 扩容长度是旧长度的1.5倍+1(因为0的1.5还是0。确切的来说应该是:+1的1.5倍, 每一次的扩容代表着创建新数组对象,复制原有数据。
     * 
     */
    private static final int DEFAULT_CAPACITY = 10;
    
    
    /**
     * 用于空实例的共享空数组实例
     * 
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};
    
    /**
     * 共享空数组实例,用于默认大小的空实例
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    
    /**
     * 存储ArrayList元素的数组缓冲区。
     * 将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会序列化到指定的目的地中。
     */
    transient Object[] elementData; 
    
    /**
     * ArrayList的大小
     */
	private int size;
    
    
    /**
     * 构造一个带有指定初始容量的空列表
     * @param initialCapacity
     */
    public ArrayList(int initialCapacity){
    	
    	//指定的初始大于0  以传进来的容量参数创建一个底层数组
    	if(initialCapacity>0){  
    		this.elementData=new Object[initialCapacity];
    	}else if(initialCapacity==0){
    		//指定初始容量等于0   创建一个空实例的共享空数组实例
    		this.elementData=EMPTY_ELEMENTDATA;
    	}else{
    		//指定初始容量为负数时,抛出非法参数异常
    		 throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);
    	}
    	
    }
    
    /**
     * 无指定的初始容量构造方法  使用默认的默认大小的空实例
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
    
    
    /**
     * 构造一个包含指定集合元素的列表,按照集合的迭代器返回的顺序
     * @param c
     */
    public ArrayList(Collection<? extends E> c) {
    	//按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组。 并赋给ArrayList元素的数组缓冲区。
        elementData = c.toArray();
        
        //判断数组和集合大小是否相等且不等于0,
        if ((size = elementData.length) != 0) {
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
        	//a.getClass()!=Object[].class,这个是因为toArray()的实现方式不同,ArrayList的toArray返回的是Object[],而其他的就可能不是
            if (elementData.getClass() != Object[].class)
                elementData = Arrays.copyOf(elementData, size, Object[].class);
        } else {
            // 等于0就创建一个空实例的共享空数组实例
            this.elementData = EMPTY_ELEMENTDATA;
        }
    }
    
    
    /**
     *将此 ArrayList 实例的容量调整为列表的当前大小。 应用程序可以使用此操作来最小化 ArrayList 实例的存储量。
     */
    public void trimToSize() {
        modCount++; //fast-fail机制,访问中如果修改集合会抛出 ConcurrentModificationException 异常  
        if (size < elementData.length) {
            elementData = (size == 0)? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size);
        }
    }
    
    
    /**
     * 增加实例的容量,如果有必要的话,可以确保它至少保留最小容量参数指定的元素个数。
     * @param minCapacity
     */
    public void ensureCapacity(int minCapacity) {
    	//如果当前的数据不为空实例,则默认初始容量为最10   为空则初始容量设为0
        int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)? 0 : DEFAULT_CAPACITY;
        //根据当前数组计算出的容量大小大于传入的容量参数 才执行增加实例的容量
        if (minCapacity > minExpand) {
            ensureExplicitCapacity(minCapacity);
        }
    }

    @SuppressWarnings("unused")
	private void ensureCapacityInternal(int minCapacity) {
        if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    /**
     * 判断是否要扩容
     * @param minCapacity
     */
    private void ensureExplicitCapacity(int minCapacity) {
        modCount++;
        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }

    /**
     * 要分配的数组的最大大小。
     * Some VMs reserve some header words in an array.
     * 尝试分配更大的数组可能会导致
     * OutOfMemoryError: 请求的数组大小超过VM限制
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    
    /**
     * 增加容量,以确保它至少能保持
     * 最小容量参数指定的元素个数。
     *
     * 每次重新分配内存时,新的容量为旧的1.5倍  
     * 但是如果分配后超过可以分配的内存范围分配Integer.MAX_VALUE大小 ,则比较要分配的和最大可分配的容量大小,如果大于分配Integer.MAX_VALUE,如果小于,分配最大容量大小  
     * @param minCapacity the desired minimum capacity
     */
    private void grow(int minCapacity) {
        // overflow-conscious code 
        int oldCapacity = elementData.length;  //获取旧数组的长度
        int newCapacity = oldCapacity + (oldCapacity >> 1); //计算新数组的长度
        //进行一些判断 为了保证新数组元素个数在正常范围内
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity;
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        //数组复制 指定长度
        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;
    }

  
    


	/**
	 * 返回列表中的元素个数。
	 */
	@Override
	public int size() {
		// TODO Auto-generated method stub
		return size;
	}

	/**
	 * 判断列表是为空
	 */
	public boolean isEmpty() {
	        return size == 0;
	}
	
	/**
	 * 是否包含指定元素
	 */
	public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
	
	/**
	 * 返回指定元素位置,若没有返回-1,查找的元素容许为null  
	 */
	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;
    }
	
	
	/**
	 * 返回指定元素最后一次出现的位置,若没有返回-1  
	 */
	 public int lastIndexOf(Object o) {
	        if (o == null) {
	            for (int i = size-1; i >= 0; i--)
	                if (elementData[i]==null)
	                    return i;
	        } else {
	            for (int i = size-1; i >= 0; i--)
	                if (o.equals(elementData[i]))
	                    return i;
	        }
	        return -1;
	  }
	 
	 
	 /**
	  * 克隆函数  
	  */
	  public Object clone() {
	        try {
	            ArrayList<?> v = (ArrayList<?>) super.clone();
	            v.elementData = Arrays.copyOf(elementData, size);
	            v.modCount = 0;
	            return v;
	        } catch (CloneNotSupportedException e) {
	            // this shouldn't happen, since we are Cloneable
	            throw new InternalError();
	        }
	    }
	  
	  /**
	   * 按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组。
	   */
	  public Object[] toArray() {
	        return Arrays.copyOf(elementData, size);
	  }
	  
	  /**
	   * 返回包含该列表中所有元素的数组
	   */
	   @SuppressWarnings("unchecked")
	   public <T> T[] toArray(T[] a) {
	        if (a.length < size)
	            // Make a new array of a's runtime type, but my contents:
	            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
	        System.arraycopy(elementData, 0, a, 0, size);
	        if (a.length > size)
	            a[size] = null;
	        return a;
	    }
	   
	   /**
	    * 位置访问操作  返回指定位置的参数
	    * @param index
	    * @return
	    */
	    @SuppressWarnings("unchecked")
	    E elementData(int index) {
	        return (E) elementData[index];
	    }

	    
	    /**
	     * 按下标取值
	     */
	    public E get(int index) {
	        rangeCheck(index);

	        return elementData(index);
	    }
		
	    /**
	     * 按下标赋值
	     */
	    public E set(int index, E element) {
	        rangeCheck(index);

	        E oldValue = elementData(index);
	        elementData[index] = element;
	        return oldValue;
	    }
	    
	    /**
	     * 检查传入的下标是否越界
	     */
	    private void rangeCheck(int index) {
	        if (index >= size)
	            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
	    }
	    
	    /**
	     * 将指定的元素添加到此列表的尾部。
	     */
	    public boolean add(E e) {
	        ensureCapacityInternal(size + 1);  // Increments modCount!!
	        elementData[size++] = e;
	        return true;
	    }
	    
	    /**
	     * 将指定的元素插入此列表中的指定位置。向右移动当前位于该位置的元素(如果有)以及所有后续元素(将其索引加 1)
	     */
	    public void add(int index, E element) {
	        rangeCheckForAdd(index);

	        ensureCapacityInternal(size + 1);  // Increments modCount!!
	        System.arraycopy(elementData, index, elementData, index + 1,
	                         size - index);
	        elementData[index] = element;
	        size++;
	    }
	    
	    
	    /**
	     * 移除此列表中指定位置上的元素。向左移动所有后续元素(将其索引减 1)
	     */
	    public E remove(int index) {
	        rangeCheck(index);

	        modCount++;
	        E oldValue = elementData(index);

	        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

	        return oldValue;
	    }
	    
	    /**
	     * 移除列表首次出现的指定元素,如果不存在返回false  
	     */
	    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 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
	    }
	    
	    /**
	     * 移除此列表中的所有元素。此调用返回后,列表将为空。
	     */
	    public void clear() {
	        modCount++;

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

	        size = 0;
	    }

	    /**
	     * 按照指定 collection 的迭代器所返回的元素顺序,将该 collection 中的所有元素添加到此列表的尾部
	     */
	    public boolean addAll(Collection<? extends E> c) {
	        Object[] a = c.toArray();
	        int numNew = a.length;
	        ensureCapacityInternal(size + numNew);  // 增加容量
	        System.arraycopy(a, 0, elementData, size, numNew);//源数组,源数组要复制的起始位置,目的数组,目的数组放置的起始位置,复制的长度
	        size += numNew;
	        return numNew != 0;
	    }
	    
	    /**
	     * 从指定的位置开始,将指定 collection 中的所有元素插入到此列表中
	     */
	    public boolean addAll(int index, Collection<? extends E> c) {
	        rangeCheckForAdd(index);

	        Object[] a = c.toArray();
	        int numNew = a.length;
	        ensureCapacityInternal(size + numNew);  // Increments modCount

	        int numMoved = size - index;
	        if (numMoved > 0)
	            System.arraycopy(elementData, index, elementData, index + numNew, numMoved);

	        System.arraycopy(a, 0, elementData, index, numNew);
	        size += numNew;
	        return numNew != 0;
	    }
	    
	     /**
	      * 从这个列表中删除索引之间的所有元素 如果开始位置和结束位置相同则无效
	      * 
	      */
	    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;
	    }
	    
	    
	 

	    /**
	     * 添加和addAll使用的rangeCheck版本。
	     */
	    private void rangeCheckForAdd(int index) {
	        if (index > size || index < 0)
	            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
	    }

	    
	    /**
	     * 构造一个IndexOutOfBoundsException细节信息。
	     */
	    private String outOfBoundsMsg(int index) {
	        return "Index: "+index+", Size: "+size;
	    }
	    
	    /**
	     * 从类 java.util.AbstractCollection 继承的方法
	     * 删除集合所有元素
	     */
	    public boolean removeAll(Collection<?> c) {
	        Objects.requireNonNull(c); 
	        return batchRemove(c, false);
	    }
	    
	   /**
	    *  从类 java.util.AbstractCollection 继承的方法
	    * 此实现在此 collection 上进行迭代,依次检查该迭代器返回的每个元素,以查看其是否包含在指定的 collection 中。如果不是,
	    * 则使用迭代器的 remove 方法将其从此 collection 中移除。
	    */
	    public boolean retainAll(Collection<?> c) {
	        Objects.requireNonNull(c);
	        return batchRemove(c, true);
	    }
	    
	    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;
	    }
	    
	  
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值