ArrayList源码分析

来源:互联网 发布:安全员网络平台 编辑:程序博客网 时间:2024/04/28 14:03


一、前言

一直就想看看java的源码,学习一下大牛的编程。这次下狠心花了几个晚上的时间,终于仔细分析了下 ArrayList 的源码(PS:谁说的一个晚上可以看完的?太瞎扯了)。现在记录一下所得。


二、ArrayList 源码分析

2.1 如何分析?

想要分析下源码是件好事,但是如何去进行分析呢?以我的例子来说,我进行源码分析的过程如下几步:

  • 找到类:利用 Eclipse 找到所需要分析的类(此处就是 ArrayList)
  • 新建类:新建一个类,命名为 ArrayList,将源码拷贝到该类。因为我们分析的时候肯定是需要进行代码注释,以及调试的,而jdk的源码,我们是没法在里面直接进行代码注释和断点调试的
  • 修改类:我们刚拷贝过来的源码,肯定会报错的。报错原因比如:包名不匹配、继承的类中权限问题,因此我们需要对源码进行修改。
  • 查看代码 + 测试案例 + 断点调试:前面准备好了,就到分析的过程了。分析,不仅仅是简单的看下代码,我们需要仔细思考,且辅以相应的测试案例,甚至于进行断点跟踪查看运行过程。
     

2.2 ArrayList 的分析

先直接将我对ArrayList的分析结果放出来,然后说一下其中的注意点。注:本人的 JDK 是 1.8 的,因此 ArrayList 中有不少是 1.8 才支持的函数,用于函数式编程。不过本人函数式编程那部分没怎么学,因此函数式编程部分没怎么分析
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. // 注意:此处我们需要将 AbstractList<E> 的源码拷贝到同包下的 AbstractList<E> 类中  
  2. // 否则若是直接使用 java.util.AbstractList,会报错,因为我们无权访问 modCount。因  
  3. // 该变量的声明为 protected transient int modCount = 0;  
  4. /** 
  5.  * ArrayList 源码分析 
  6.  * - 继承:抽象类 java.util.AbstractList<E> 
  7.  * - 实现:java.util.List<E>,java.util.List<E>,java.util.List<E>,java.io.Serializable 
  8.  * - 本类的实现中,大量调用了 System.arraycopy()  和 Arrays.copyOf() 方法 
  9.  *  
  10.  * 几个工具类:System、Arrays、Objects 
  11.  * @author johnnie 
  12.  * @time 2016年5月15日 
  13.  * @param <E> 
  14.  */  
  15. public class ArrayList<E>  extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {  
  16.   
  17.     /** 
  18.      * 序列号 
  19.      */  
  20.     private static final long serialVersionUID = 8683452581122892189L;  
  21.   
  22.     /** 
  23.      * 默认容量 
  24.      */  
  25.     private static final int DEFAULT_CAPACITY = 10;  
  26.   
  27.     /** 
  28.      * 一个空数组 
  29.      * - 当用户指定该 ArrayList 容量为 0 时,返回该空数组 
  30.      * - ArrayList(int initialCapacity) 
  31.      */  
  32.     private static final Object[] EMPTY_ELEMENTDATA = {};  
  33.   
  34.     /** 
  35.      * 一个空数组实例 
  36.      * - 当用户没有指定 ArrayList 的容量时(即调用无参构造函数),返回的是该数组==>刚创建一个 ArrayList 时,其内数据量为 0。 
  37.      * - 当用户第一次添加元素时,该数组将会扩容,变成默认容量为 10(DEFAULT_CAPACITY) 的一个数组===>通过  ensureCapacityInternal() 实现 
  38.      *  
  39.      * 它与 EMPTY_ELEMENTDATA 的区别就是:该数组是默认返回的,而后者是在用户指定容量为 0 时返回 
  40.      */  
  41.     private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};  
  42.   
  43.     /** 
  44.      * ArrayList基于数组实现,用该数组保存数据, ArrayList 的容量就是该数组的长度 
  45.      * - 该值为 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 时,当第一次添加元素进入 ArrayList 中时,数组将扩容值 DEFAULT_CAPACITY(10) 
  46.      */  
  47.     transient Object[] elementData; // non-private to simplify nested class access  
  48.   
  49.     /** 
  50.      * ArrayList实际存储的数据数量 
  51.      */  
  52.     private int size;  
  53.   
  54.     /** 
  55.      * 创建一个初试容量的、空的ArrayList 
  56.      * - 可能报错: java.lang.OutOfMemoryError: Requested array size exceeds VM limit 
  57.      * @param  initialCapacity  初始容量 
  58.      * @throws IllegalArgumentException 当初试容量值非法(小于0)时抛出 
  59.      */  
  60.     public ArrayList(int initialCapacity) {  
  61.         if (initialCapacity > 0) {  
  62.             this.elementData = new Object[initialCapacity];  
  63.         } else if (initialCapacity == 0) {  
  64.             // 数组缓冲区为 EMPTY_ELEMENTDATA,注意与 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 的区别  
  65.             this.elementData = EMPTY_ELEMENTDATA;  
  66.         } else {  
  67.             throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);  
  68.         }  
  69.     }  
  70.       
  71.     /** 
  72.      * 无参构造函数: 
  73.      * - 创建一个 空的 ArrayList,此时其内数组缓冲区 elementData = {}, 长度为 0 
  74.      * - 当元素第一次被加入时,扩容至默认容量 10 
  75.      */  
  76.     public ArrayList() {  
  77.         this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;  
  78.     }  
  79.   
  80.     /** 
  81.      * Constructs a list containing the elements of the specified 
  82.      * collection, in the order they are returned by the collection's 
  83.      * iterator. 
  84.      *  
  85.      * 创建一个包含collection的ArrayList 
  86.      * 
  87.      * @param c 要放入 ArrayList 中的集合,其内元素将会全部添加到新建的 ArrayList 实例中 
  88.      * @throws NullPointerException 当参数 c 为 null 时抛出异常 
  89.      */  
  90.     public ArrayList(Collection<? extends E> c) {  
  91.         elementData = c.toArray();                      // 集合转 Object[] 数组  
  92.         // 将转换后的 Object[] 长度赋值给当前 ArrayList 的 size,并判断是否为 0  
  93.         if ((size = elementData.length) != 0) {  
  94.             // c.toArray might (incorrectly) not return Object[] (see 6260652)  
  95.             // 这句话意思是:c.toArray 可能不会返回 Object[],可以查看 java 官方编号为 6260652 的 bug  
  96.             if (elementData.getClass() != Object[].class)  
  97.                 // 若 c.toArray() 返回的数组类型不是 Object[],则利用 Arrays.copyOf(); 来构造一个大小为 size 的 Object[] 数组  
  98.                 elementData = Arrays.copyOf(elementData, size, Object[].class);  
  99.         } else {  
  100.             // 换成空数组  
  101.             this.elementData = EMPTY_ELEMENTDATA;  
  102.         }  
  103.     }  
  104.   
  105.     /** 
  106.      * 将数组缓冲区大小调整到实际 ArrayList 存储元素的大小,即 elementData = Arrays.copyOf(elementData, size); 
  107.      * - 该方法由用户手动调用,以减少空间资源浪费的目的 
  108.      */  
  109.     public void trimToSize() {  
  110.         // modCount 是 AbstractList 的属性值:protected transient int modCount = 0;  
  111.         // [问] modCount 有什么用?  
  112.         modCount++;                               
  113.         // 当实际大小 < 数组缓冲区大小时  
  114.         // 如调用默认构造函数后,刚添加一个元素,此时 elementData.length = 10,而 size = 1  
  115.         // 通过这一步,可以使得空间得到有效利用,而不会出现资源浪费的情况  
  116.         if (size < elementData.length) {  
  117.             // 注意这里:这里的执行顺序不是 (elementData = (size == 0) ) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size);  
  118.             // 而是:elementData = ((size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size));  
  119.             // 这里是运算符优先级的语法  
  120.             // 调整数组缓冲区 elementData,变为实际存储大小 Arrays.copyOf(elementData, size)  
  121.             elementData = (size == 0) ? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size);  
  122.         }  
  123.     }  
  124.   
  125.     /** 
  126.      * 指定 ArrayList 的容量 
  127.      * @param   minCapacity   指定的最小容量 
  128.      */  
  129.     public void ensureCapacity(int minCapacity) {  
  130.         // 最小扩充容量,默认是 10  
  131.         int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;  
  132.           
  133.         // 若用户指定的最小容量 > 最小扩充容量,则以用户指定的为准,否则还是 10  
  134.         if (minCapacity > minExpand) {  
  135.             ensureExplicitCapacity(minCapacity);      
  136.         }  
  137.     }  
  138.   
  139.     /** 
  140.      * 私有方法:明确 ArrarList 的容量,提供给本类使用的方法 
  141.      * - 用于内部优化,保证空间资源不被浪费:尤其在 add() 方法添加时起效 
  142.      * @param minCapacity    指定的最小容量 
  143.      */  
  144.     private void ensureCapacityInternal(int minCapacity) {  
  145.         // 若 elementData == {},则取 minCapacity 为 默认容量和参数 minCapacity 之间的最大值  
  146.         // 注:ensureCapacity() 是提供给用户使用的方法,在 ArrayList 的实现中并没有使用  
  147.         if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {  
  148.             minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);  
  149.         }  
  150.   
  151.         ensureExplicitCapacity(minCapacity);      
  152.     }  
  153.       
  154.     /** 
  155.      * 私有方法:明确 ArrayList 的容量 
  156.      * - 用于内部优化,保证空间资源不被浪费:尤其在 add() 方法添加时起效 
  157.      * @param minCapacity    指定的最小容量 
  158.      */  
  159.     private void ensureExplicitCapacity(int minCapacity) {  
  160.         // 将“修改统计数”+1,该变量主要是用来实现fail-fast机制的   
  161.         modCount++;  
  162.   
  163.         // 防止溢出代码:确保指定的最小容量 > 数组缓冲区当前的长度  
  164.         if (minCapacity - elementData.length > 0)  
  165.             grow(minCapacity);  
  166.     }  
  167.   
  168.     /** 
  169.      * 数组缓冲区最大存储容量 
  170.      * - 一些 VM 会在一个数组中存储某些数据--->为什么要减去 8 的原因 
  171.      * - 尝试分配这个最大存储容量,可能会导致 OutOfMemoryError(当该值 > VM 的限制时) 
  172.      */  
  173.     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;  
  174.   
  175.     /** 
  176.      * 私有方法:扩容,以确保 ArrayList 至少能存储 minCapacity 个元素 
  177.      * - 扩容计算:newCapacity = oldCapacity + (oldCapacity >> 1);  
  178.      * @param minCapacity    指定的最小容量 
  179.      */  
  180.     private void grow(int minCapacity) {  
  181.         // 防止溢出代码  
  182.         int oldCapacity = elementData.length;  
  183.         // 运算符 >> 是带符号右移. 如 oldCapacity = 10,则 newCapacity = 10 + (10 >> 1) = 10 + 5 = 15  
  184.         int newCapacity = oldCapacity + (oldCapacity >> 1);     
  185.         if (newCapacity - minCapacity < 0)                   // 若 newCapacity 依旧小于 minCapacity  
  186.             newCapacity = minCapacity;  
  187.         if (newCapacity - MAX_ARRAY_SIZE > 0)            // 若 newCapacity 大于最大存储容量,则进行大容量分配  
  188.             newCapacity = hugeCapacity(minCapacity);  
  189.         // minCapacity is usually close to size, so this is a win:  
  190.         elementData = Arrays.copyOf(elementData, newCapacity);  
  191.     }  
  192.   
  193.     /** 
  194.      * 私有方法:大容量分配,最大分配 Integer.MAX_VALUE 
  195.      * @param minCapacity 
  196.      * @return 
  197.      */  
  198.     private static int hugeCapacity(int minCapacity) {  
  199.         if (minCapacity < 0// overflow  
  200.             throw new OutOfMemoryError();  
  201.         return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;  
  202.     }  
  203.   
  204.     /** 
  205.      * 获取该 list 所实际存储的元素个数 
  206.      * @return list 所实际存储的元素个数 
  207.      */  
  208.     public int size() {  
  209.         return size;  
  210.     }  
  211.   
  212.     /** 
  213.      * 判断 list 是否为空 
  214.      * @return ture?空:非空 
  215.      */  
  216.     public boolean isEmpty() {  
  217.         return size == 0;               // 直接看 size 是否为 0,没有先调用 size() 然后判断  
  218.     }  
  219.   
  220.     /** 
  221.      * 判断该 ArrayList 是否包含指定对象(Object 类型) 
  222.      * - 面对抽象编程,向上转型是安全的 
  223.      * @param o  
  224.      * @return <tt>true</tt>?包含:不包含 
  225.      */  
  226.     public boolean contains(Object o) {  
  227.         // 根据 indexOf() 的值(索引值)来判断,大于等于 0 就包含  
  228.         // 注意:等于 0 的情况不能漏,因为索引号是从 0 开始计数的  
  229.         return indexOf(o) >= 0;  
  230.     }  
  231.   
  232.     /** 
  233.      * 顺序查找,返回元素的最低索引值(最首先出现的索引位置) 
  234.      * @return 存在?最低索引值:-1 
  235.      */  
  236.     public int indexOf(Object o) {  
  237.         if (o == null) {                                // 注意:元素为 null 并非表示这是非法操作。空值也可以作为元素放入 ArrayList  
  238.             for (int i = 0; i < size; i++)       // 顺序查找数组缓冲区。注意:Arrays 工具类提供了二分搜索,但没有提供顺序查找  
  239.                 if (elementData[i]==null)  
  240.                     return i;  
  241.         } else {  
  242.             for (int i = 0; i < size; i++)  
  243.                 if (o.equals(elementData[i]))  
  244.                     return i;  
  245.         }  
  246.         return -1;  
  247.     }  
  248.   
  249.     /** 
  250.      * 反向查找(从数组末尾向开始查找),返回元素的最高索引值 
  251.      * @return 存在?最高索引值:-1 
  252.      */  
  253.     public int lastIndexOf(Object o) {  
  254.         if (o == null) {  
  255.             for (int i = size-1; i >= 0; i--)            // 逆序查找  
  256.                 if (elementData[i]==null)  
  257.                     return i;  
  258.         } else {  
  259.             for (int i = size-1; i >= 0; i--)  
  260.                 if (o.equals(elementData[i]))  
  261.                     return i;  
  262.         }  
  263.         return -1;  
  264.     }  
  265.   
  266.     /** 
  267.      * 深度复制:对拷贝出来的 ArrayList 对象的操作,不会影响原来的 ArrayList 
  268.      * @return 一个克隆的 ArrayList 实例(深度复制的结果) 
  269.      */  
  270.     public Object clone() {  
  271.         try {  
  272.             // Object 的克隆方法:会复制本对象及其内所有基本类型成员和 String 类型成员,但不会复制对象成员、引用对象  
  273.             ArrayList<?> v = (ArrayList<?>) super.clone();  
  274.             // 对需要进行复制的引用变量,进行独立的拷贝:将存储的元素移入新的 ArrayList 中  
  275.             v.elementData = Arrays.copyOf(elementData, size);  
  276.             v.modCount = 0;  
  277.             return v;  
  278.         } catch (CloneNotSupportedException e) {  
  279.             throw new InternalError(e);  
  280.         }  
  281.     }  
  282.       
  283.   
  284.     /** 
  285.      * 返回 ArrayList 的 Object 数组 
  286.      * - 包含 ArrayList 的所有储存元素 
  287.      * - 对返回的该数组进行操作,不会影响该 ArrayList(相当于分配了一个新的数组)==>该操作是安全的 
  288.      * - 元素存储顺序与 ArrayList 中的一致 
  289.      * @return  
  290.      */  
  291.     public Object[] toArray() {  
  292.         return Arrays.copyOf(elementData, size);  
  293.     }  
  294.   
  295.     /** 
  296.      * 返回 ArrayList 元素组成的数组 
  297.      * @param a 需要存储 list 中元素的数组 
  298.      * 若 a.length >= list.size,则将 list 中的元素按顺序存入 a 中,然后 a[list.size] = null, a[list.size + 1] 及其后的元素依旧是 a 的元素 
  299.      * 否则,将返回包含list 所有元素且数组长度等于 list 中元素个数的数组 
  300.      * 注意:若 a 中本来存储有元素,则 a 会被 list 的元素覆盖,且 a[list.size] = null 
  301.      * @return  
  302.      * @throws ArrayStoreException 当 a.getClass() != list 中存储元素的类型时 
  303.      * @throws NullPointerException 当 a 为 null 时 
  304.      */  
  305.     @SuppressWarnings("unchecked")  
  306.     public <T> T[] toArray(T[] a) {  
  307.         // 若数组a的大小 < ArrayList的元素个数,则新建一个T[]数组,数组大小是"ArrayList的元素个数",并将“ArrayList”全部拷贝到新数组中  
  308.         if (a.length < size)  
  309.             return (T[]) Arrays.copyOf(elementData, size, a.getClass());  
  310.           
  311.         // 若数组a的大小 >= ArrayList的元素个数,则将ArrayList的全部元素都拷贝到数组a中。  
  312.         System.arraycopy(elementData, 0, a, 0, size);  
  313.         if (a.length > size)  
  314.             // a[list.size] = null  
  315.             a[size] = null;  
  316.         return a;  
  317.     }  
  318.   
  319.     // Positional Access Operations  
  320.       
  321.     /** 
  322.      * 返回在索引为 index 的元素:数组的随机访问  
  323.      * - 默认包访问权限 
  324.      *  
  325.      * 封装粒度很强,连数组随机取值都封装为一个方法。 
  326.      * 主要是避免每次取值都要强转===>设置值就没有封装成一个方法,因为设置值不需要强转 
  327.      * @param index 
  328.      * @return 
  329.      */  
  330.     @SuppressWarnings("unchecked")  
  331.     E elementData(int index) {  
  332.         return (E) elementData[index];  
  333.     }  
  334.   
  335.     /** 
  336.      * 获取指定位置的元素:从 0 开始计数 
  337.      * @param  index 元素索引 
  338.      * @return 存储在 index 位置的元素 
  339.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  340.      */  
  341.     public E get(int index) {  
  342.         rangeCheck(index);                  // 检查是否越界  
  343.   
  344.         return elementData(index);      // 随机访问  
  345.     }  
  346.   
  347.     /** 
  348.      * 设置 index 位置元素的值 
  349.      * @param index 索引值 
  350.      * @param element 需要存储在 index 位置的元素值 
  351.      * @return 替换前在 index 位置的元素值 
  352.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  353.      */  
  354.     public E set(int index, E element) {  
  355.         rangeCheck(index);                          //  数组越界检查  
  356.   
  357.         E oldValue = elementData(index);        // 取出旧值  
  358.         elementData[index] = element;           // 替换成新值  
  359.         return oldValue;  
  360.     }  
  361.   
  362.     /** 
  363.      * 添加新值到 list 末尾 
  364.      * @param e 添加的值 
  365.      * @return <tt>true</tt> 
  366.      */  
  367.     public boolean add(E e) {  
  368.         // 确定ArrayList的容量大小---严谨  
  369.         // 注意:size + 1,保证资源空间不被浪费,按当前情况,保证要存多少个元素,就只分配多少空间资源  
  370.         ensureCapacityInternal(size + 1);  // Increments modCount!!  
  371.         // 添加 e 到 ArrayList 中,然后 size 自增 1  
  372.         elementData[size++] = e;  
  373.         return true;  
  374.     }  
  375.   
  376.     /** 
  377.      * 插入方法,其实应该命名为 insert() 比较合理 
  378.      * - 在指定位置插入新元素,原先在 index 位置的值往后移动一位 
  379.      * @param 要插入的位置 
  380.      * @param 要插入的元素 
  381.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  382.      */  
  383.     public void add(int index, E element) {  
  384.         rangeCheckForAdd(index);  
  385.   
  386.         ensureCapacityInternal(size + 1);  // Increments modCount!!  
  387.         System.arraycopy(elementData, index, elementData, index + 1,  
  388.                          size - index);  
  389.         elementData[index] = element;  
  390.         size++;  
  391.     }  
  392.   
  393.     /** 
  394.      * 移除指定索引位置的元素:index 之后的所有元素依次左移一位 
  395.      * @param index  
  396.      * @return 被移出的元素 
  397.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  398.      */  
  399.     public E remove(int index) {  
  400.         rangeCheck(index);                          // 越界检查  
  401.   
  402.         modCount++;  
  403.         E oldValue = elementData(index);        // 旧值  
  404.   
  405.         int numMoved = size - index - 1;        // 需要左移的元素个数  
  406.         if (numMoved > 0)  
  407.             // 左移:利用 System.arraycopy() 进行左移一位的操作  
  408.             // 将 elementData(源数组)从下标为 index+1 开始的元素,拷贝到 elementData(目标数组)下标为 index 的位置,总共拷贝 numMoved 个  
  409.             System.arraycopy(elementData, index+1, elementData, index, numMoved);  
  410.         elementData[--size] = null;                 // 将最后一个元素置空  
  411.   
  412.         return oldValue;  
  413.     }  
  414.   
  415.     /** 
  416.      * 删除 ArrayList 中的一个指定元素(符合条件的索引最低) 
  417.      * - 只会删除一个 
  418.      * - 删除的那个元素,是符合条件的结果中索引号最低的那个 
  419.      * - 若不包含要删除的元素,则返回 false 
  420.      *  
  421.      * 相比 remove(index):该方法并没有进行越界检查,即调用 rangeCheck()  
  422.      *  
  423.      * @param o 要删除的元素 
  424.      * @return <tt>true</tt> ? ArrayList中包含该元素,删除成功:不包含该元素,删除失败 
  425.      */  
  426.     public boolean remove(Object o) {  
  427.         if (o == null) {  
  428.             for (int index = 0; index < size; index++)  
  429.                 if (elementData[index] == null) {       // 判断是否存储了 null   
  430.                     fastRemove(index);  
  431.                     return true;  
  432.                 }  
  433.         } else {  
  434.              // 遍历ArrayList,找到“元素o”,则删除,并返回true  
  435.             for (int index = 0; index < size; index++)  
  436.                 if (o.equals(elementData[index])) {     // 利用 equals 判断两对象值是否相等(equals 比较值,== 比较引用)  
  437.                     fastRemove(index);  
  438.                     return true;  
  439.                 }  
  440.         }  
  441.           
  442.         return false;  
  443.     }  
  444.   
  445.     /* 
  446.      * 私有方法:快速删除第 index 个元素 
  447.      * - 该方法会跳过越界检查 
  448.      */  
  449.     private void fastRemove(int index) {  
  450.         modCount++;  
  451.         int numMoved = size - index - 1;  
  452.         // 左移操作  
  453.         if (numMoved > 0)  
  454.             System.arraycopy(elementData, index+1, elementData, index,  
  455.                              numMoved);  
  456.           
  457.         elementData[--size] = null;         //  将最后一个元素设为null  
  458.     }  
  459.   
  460.     /** 
  461.      * 清空所有存储元素 
  462.      * - 它会将数组缓冲区所以元素置为 null 
  463.      * - 清空后,我们直接打印 list,却只会看见一个 [], 而不是 [null, null, ....] ==> toString() 和 迭代器进行了处理 
  464.      */  
  465.     public void clear() {  
  466.         modCount++;  
  467.   
  468.         // clear to let GC do its work  
  469.         for (int i = 0; i < size; i++)  
  470.             elementData[i] = null;  
  471.   
  472.         size = 0;  
  473.     }  
  474.       
  475.     /**  
  476.      * 将一个集合的所有元素顺序添加(追加)到 lits 末尾 
  477.      * - ArrayList 是线程不安全的。 
  478.      * - 该方法没有加锁,当一个线程正在将 c 中的元素加入 list 中,但同时有另一个线程在更改 c 中的元素,可能会有问题 
  479.      * @param c collection containing elements to be added to this list 
  480.      * @return <tt>true</tt> ? list 元素个数有改变时,成功:失败 
  481.      * @throws NullPointerException 当 c 为 null 时 
  482.      */  
  483.     public boolean addAll(Collection<? extends E> c) {  
  484.         Object[] a = c.toArray();                               // 若 c 为 null,此行将抛出空指针异常  
  485.         int numNew = a.length;                          // 要添加的元素个数  
  486.         ensureCapacityInternal(size + numNew);  // 扩容,Increments modCount  
  487.         System.arraycopy(a, 0, elementData, size, numNew);  // 添加  
  488.         size += numNew;  
  489.           
  490.         return numNew != 0;  
  491.     }  
  492.   
  493.     /** 
  494.      * 从 index 位置开始,将集合 c 中的元素添加到ArrayList 
  495.      * - 并不会覆盖掉在 index 位置原有的值 
  496.      * - 类似于 insert 操作,在 index 处插入 c.length 个元素(原来在此处的 n 个元素依次右移) 
  497.      * @param index 插入位置 
  498.      * @param c  
  499.      * @return <tt>true</tt> ? list 元素个数有改变时,成功:失败 
  500.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  501.      * @throws NullPointerException 当 c 为 null 时 
  502.      */  
  503.     public boolean addAll(int index, Collection<? extends E> c) {  
  504.         rangeCheckForAdd(index);                        // 越界检查  
  505.   
  506.         Object[] a = c.toArray();                               // 空指针异常抛出点  
  507.         int numNew = a.length;  
  508.         ensureCapacityInternal(size + numNew);  // 扩容,Increments modCount  
  509.   
  510.         int numMoved = size - index;                    // 要移动的元素个数  
  511.         /*  
  512.          * 先元素移动,在拷贝,以免被覆盖 
  513.          */  
  514.         if (numMoved > 0)                                      
  515.             System.arraycopy(elementData, index, elementData, index + numNew,  
  516.                              numMoved);  
  517.   
  518.         System.arraycopy(a, 0, elementData, index, numNew);  
  519.         size += numNew;  
  520.         return numNew != 0;  
  521.     }  
  522.   
  523.     /** 
  524.      * Removes from this list all of the elements whose index is between 
  525.      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. 
  526.      * Shifts any succeeding elements to the left (reduces their index). 
  527.      * This call shortens the list by {@code (toIndex - fromIndex)} elements. 
  528.      * (If {@code toIndex==fromIndex}, this operation has no effect.) 
  529.      *  
  530.      * 删除fromIndex到toIndex之间的全部元素 
  531.      *  
  532.      * @throws IndexOutOfBoundsException if {@code fromIndex} or 
  533.      *         {@code toIndex} is out of range 
  534.      *         ({@code fromIndex < 0 || 
  535.      *          fromIndex >= size() || 
  536.      *          toIndex > size() || 
  537.      *          toIndex < fromIndex}) 
  538.      */  
  539.     protected void removeRange(int fromIndex, int toIndex) {  
  540.         modCount++;  
  541.         int numMoved = size - toIndex;  
  542.         /* 
  543.          * 利用 System.arraycopy() 进行元素拷贝,再让失去价值的元素置为 null 
  544.          */  
  545.         System.arraycopy(elementData, toIndex, elementData, fromIndex,  
  546.                          numMoved);  
  547.   
  548.         // clear to let GC do its work  
  549.         int newSize = size - (toIndex-fromIndex);       // 删除后,list 的长度  
  550.         for (int i = newSize; i < size; i++) {               // 清除失去价值的元素  
  551.             elementData[i] = null;  
  552.         }  
  553.         size = newSize;  
  554.     }  
  555.   
  556.     /** 
  557.      *  
  558.      * - 提供给 get()、remove() 等方法:检查给出的索引值 index 是否越界(大于或等于 list.size) 
  559.      * 注:该方法并没有检查 index 是否合法(如小于 0,这个是由数组类型自己检查的) 
  560.      */  
  561.     private void rangeCheck(int index) {  
  562.         if (index >= size)  
  563.             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));  
  564.     }  
  565.   
  566.     /** 
  567.      * 提供给 add() 和 add() 进行数组越界检查的方法 
  568.      */  
  569.     private void rangeCheckForAdd(int index) {  
  570.         if (index > size || index < 0)  
  571.             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));  
  572.     }  
  573.   
  574.     /** 
  575.      * 返回异常消息,用于传给 IndexOutOfBoundsException 
  576.      */  
  577.     private String outOfBoundsMsg(int index) {  
  578.         return "Index: "+index+", Size: "+size;  
  579.     }  
  580.   
  581.     /** 
  582.      * 移除 list 中和 c 中共有的元素 
  583.      * - 若实例化 Collection 的类不是 ArrayList,则删除肯定失败 
  584.      *  
  585.      * @param c  
  586.      * @return true ? 若 c 和 list 有公有元素,删除成功(或list元素个数有改变) : 没有公有元素,删除失败 
  587.      * @throws ClassCastException 
  588.      * @throws NullPointerException 若 c 为 null 时 
  589.      * @see Collection#contains(Object) 
  590.      */  
  591.     public boolean removeAll(Collection<?> c) {  
  592.         Objects.requireNonNull(c);              // 当 c == null,则改行抛出空指针异常  
  593.         return batchRemove(c, false);  
  594.     }  
  595.   
  596.     /** 
  597.      * 只保留 list 和 集合 c 中公有的元素:和 removeAll() 功能相反 
  598.      * @param c  
  599.      * @return true ? list 元素个数有改变 
  600.      * @throws ClassCastException  
  601.      * @throws NullPointerException  
  602.      * @see Collection#contains(Object) 
  603.      */  
  604.     public boolean retainAll(Collection<?> c) {  
  605.         Objects.requireNonNull(c);  
  606.         return batchRemove(c, true);  
  607.     }  
  608.   
  609.     /** 
  610.      * 批量删除 
  611.      * @param c 
  612.      * @param complement 是否取补集 
  613.      * @return 
  614.      */  
  615.     private boolean batchRemove(Collection<?> c, boolean complement) {  
  616.         final Object[] elementData = this.elementData;  
  617.         int r = 0, w = 0;  
  618.         boolean modified = false;  
  619.         try {  
  620.             for (; r < size; r++)  
  621.                 if (c.contains(elementData[r]) == complement)  
  622.                     elementData[w++] = elementData[r];  
  623.         } finally {  
  624.             // Preserve behavioral compatibility with AbstractCollection,  
  625.             // even if c.contains() throws.  
  626.             if (r != size) {  
  627.                 System.arraycopy(elementData, r,  
  628.                                  elementData, w,  
  629.                                  size - r);  
  630.                 w += size - r;  
  631.             }  
  632.             if (w != size) {  
  633.                 // clear to let GC do its work  
  634.                 for (int i = w; i < size; i++)  
  635.                     elementData[i] = null;  
  636.                 modCount += size - w;  
  637.                 size = w;  
  638.                 modified = true;  
  639.             }  
  640.         }  
  641.         return modified;  
  642.     }  
  643.   
  644.     /** 
  645.      * 序列化函数 
  646.      * @serialData  
  647.      */  
  648.     private void writeObject(ObjectOutputStream s) throws IOException{  
  649.         int expectedModCount = modCount;  
  650.         s.defaultWriteObject();  
  651.   
  652.         // 写入ArrayList大小   
  653.         s.writeInt(size);  
  654.   
  655.         // 写入存储的元素  
  656.         for (int i=0; i<size; i++) {  
  657.             s.writeObject(elementData[i]);  
  658.         }  
  659.   
  660.         if (modCount != expectedModCount) {  
  661.             throw new ConcurrentModificationException();  
  662.         }  
  663.     }  
  664.   
  665.     /** 
  666.      * 先将ArrayList的“容量”读出,然后将“所有的元素值”读出 
  667.      */  
  668.     private void readObject(java.io.ObjectInputStream s)  
  669.         throws java.io.IOException, ClassNotFoundException {  
  670.         elementData = EMPTY_ELEMENTDATA;  
  671.   
  672.         // Read in size, and any hidden stuff  
  673.         s.defaultReadObject();  
  674.   
  675.         // 从输入流中读取ArrayList的size   
  676.         s.readInt(); // ignored  
  677.   
  678.         if (size > 0) {  
  679.             ensureCapacityInternal(size);  
  680.   
  681.             Object[] a = elementData;  
  682.             // 从输入流中将“所有的元素值”读出  
  683.             for (int i=0; i<size; i++) {  
  684.                 a[i] = s.readObject();  
  685.             }  
  686.         }  
  687.     }  
  688.   
  689.     /** 
  690.      * 返回一个 ListIterator 
  691.      * @index 元素的索引位置 
  692.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  693.      */  
  694.     public ListIterator<E> listIterator(int index) {  
  695.         if (index < 0 || index > size)  
  696.             throw new IndexOutOfBoundsException("Index: "+index);  
  697.         return new ListItr(index);  
  698.     }  
  699.   
  700.     /** 
  701.      * 返回一个 ListIterator 迭代器,该迭代器是 fail-fast 机制的 
  702.      */  
  703.     public ListIterator<E> listIterator() {  
  704.         return new ListItr(0);  
  705.     }  
  706.   
  707.     /** 
  708.      * 返回一个 Iterator 迭代器,该迭代器是 fail-fast 机制的 
  709.      * @return 
  710.      */  
  711.     public Iterator<E> iterator() {  
  712.         return new Itr();  
  713.     }  
  714.   
  715.     /** 
  716.      * AbstractList.Itr 的优化版本 
  717.      */  
  718.     private class Itr implements Iterator<E> {  
  719.         int cursor;                                                     // 下一个返回元素的索引,默认值为 0  
  720.         int lastRet = -1;                                           // 上一个返回元素的索引,若没有上一个元素,则为 -1。每次调用 remove(),lastRet 都会重置为 -1  
  721.         int expectedModCount = modCount;  
  722.   
  723.         public boolean hasNext() {  
  724.             return cursor != size;                              // 是否有下一元素的判断  
  725.         }  
  726.   
  727.         @SuppressWarnings("unchecked")  
  728.         public E next() {  
  729.             checkForComodification();  
  730.             // 临时变量 i,指向游标当前位置。  
  731.             // 此处并没有让 lastRet 直接等于 cursor 进行操作  
  732.             int i = cursor;                                                               
  733.             if (i >= size)                                                                   //  第一次检查  
  734.                 throw new NoSuchElementException();  
  735.             Object[] elementData = ArrayList.this.elementData;  
  736.             if (i >= elementData.length)                                         // 第二次检查  
  737.                 throw new ConcurrentModificationException();  
  738.             cursor = i + 1;  
  739.             return (E) elementData[lastRet = i];                                // 注意这里的取值  
  740.         }  
  741.   
  742.         public void remove() {  
  743.             if (lastRet < 0)  
  744.                 throw new IllegalStateException();  
  745.             checkForComodification();  
  746.   
  747.             try {  
  748.                 ArrayList.this.remove(lastRet);                                 // 移除元素  
  749.                 cursor = lastRet;                                                       // 指针回移  
  750.                 // 注意此处:上一元素指针直接重置为 -1。因此 lastRet 不一定就等于 cursour - 1  
  751.                 lastRet = -1;                                                                 
  752.                 expectedModCount = modCount;  
  753.             } catch (IndexOutOfBoundsException ex) {  
  754.                 throw new ConcurrentModificationException();  
  755.             }  
  756.         }  
  757.   
  758.         /** 
  759.          * jdk1.8 使用,进行函数式编程 
  760.          * 注:Consumer 是 1.8 开始有的。Since:1.8 
  761.          * @param consumer 动作,让集合每一个元素都执行该动作 
  762.          */  
  763.         @Override  
  764.         @SuppressWarnings("unchecked")  
  765.         public void forEachRemaining(Consumer<? super E> consumer) {  
  766.             Objects.requireNonNull(consumer);                               // 非空判断  
  767.             final int size = ArrayList.this.size;  
  768.             int i = cursor;  
  769.             if (i >= size) {  
  770.                 return;  
  771.             }  
  772.             final Object[] elementData = ArrayList.this.elementData;  
  773.             if (i >= elementData.length) {  
  774.                 throw new ConcurrentModificationException();  
  775.             }  
  776.             while (i != size && modCount == expectedModCount) {  
  777.                 consumer.accept((E) elementData[i++]);  
  778.             }  
  779.             // update once at end of iteration to reduce heap write traffic  
  780.             cursor = i;  
  781.             lastRet = i - 1;  
  782.             checkForComodification();  
  783.         }  
  784.   
  785.         final void checkForComodification() {  
  786.             if (modCount != expectedModCount)  
  787.                 throw new ConcurrentModificationException();  
  788.         }  
  789.     }  
  790.     /*------------------------------------- Itr 结束 -------------------------------------------*/  
  791.   
  792.     /** 
  793.      * AbstractList.ListItr 的优化版本 
  794.      * ListIterator 与普通的 Iterator 的区别: 
  795.      * - 它可以进行双向移动,而普通的迭代器只能单向移动 
  796.      * - 它可以添加元素(有 add() 方法),而后者不行 
  797.      */  
  798.     private class ListItr extends Itr implements ListIterator<E> {  
  799.         ListItr(int index) {  
  800.             super();  
  801.             cursor = index;                                             // cursor 还是指向下一个返回元素的索引位置  
  802.         }  
  803.           
  804.         /** 
  805.          * 是否有上一个元素 
  806.          * @return true ? 有:无 
  807.          */  
  808.         public boolean hasPrevious() {                        
  809.             return cursor != 0;  
  810.         }  
  811.   
  812.         /** 
  813.          * 获取下一个元素的索引 
  814.          */  
  815.         public int nextIndex() {  
  816.             return cursor;  
  817.         }  
  818.   
  819.         /** 
  820.          * 获取 cursor 前一个元素的索引 
  821.          * - 是 cursor 前一个,而不是当前元素前一个的索引。 
  822.          * - 若调用 next() 后马上调用该方法,则返回的是当前元素的索引。 
  823.          * - 若调用 next() 后想获取当前元素前一个元素的索引,需要连续调用两次该方法。 
  824.          */  
  825.         public int previousIndex() {  
  826.             return cursor - 1;  
  827.         }  
  828.   
  829.         /** 
  830.          * 返回 cursor 前一元素 
  831.          *注意事项同 previousIndex 
  832.          */  
  833.         @SuppressWarnings("unchecked")  
  834.         public E previous() {  
  835.             checkForComodification();  
  836.             int i = cursor - 1;  
  837.             if (i < 0)  
  838.                 throw new NoSuchElementException();  
  839.             Object[] elementData = ArrayList.this.elementData;  
  840.             if (i >= elementData.length)  
  841.                 throw new ConcurrentModificationException();  
  842.             cursor = i;  
  843.             return (E) elementData[lastRet = i];  
  844.         }  
  845.   
  846.         public void set(E e) {  
  847.             if (lastRet < 0)  
  848.                 throw new IllegalStateException();  
  849.             checkForComodification();  
  850.   
  851.             try {  
  852.                 ArrayList.this.set(lastRet, e);  
  853.             } catch (IndexOutOfBoundsException ex) {  
  854.                 throw new ConcurrentModificationException();  
  855.             }  
  856.         }  
  857.           
  858.         /** 
  859.          * 添加元素:在游标当前指向的索引位置插入一个元素 
  860.          */  
  861.         public void add(E e) {  
  862.             checkForComodification();  
  863.   
  864.             try {  
  865.                 int i = cursor;  
  866.                 ArrayList.this.add(i, e);  
  867.                 cursor = i + 1;  
  868.                 lastRet = -1;  
  869.                 expectedModCount = modCount;  
  870.             } catch (IndexOutOfBoundsException ex) {  
  871.                 throw new ConcurrentModificationException();  
  872.             }  
  873.         }  
  874.     }  
  875.     /*------------------------------------- ListItr 结束 -------------------------------------------*/  
  876.   
  877.     /** 
  878.      * 获取从 fromIndex 到 toIndex 之间的子集合(左闭右开区间) 
  879.      * - 若 fromIndex == toIndex,则返回的空集合 
  880.      * - 对该子集合的操作,会影响原有集合 
  881.      * - 当调用了 subList() 后,若对原有集合进行删除操作(删除subList 中的首个元素)时,会抛出异常 java.util.ConcurrentModificationException 
  882.      * - 该子集合支持所有的集合操作 
  883.      *  
  884.      * 原因看 SubList 内部类的构造函数就可以知道 
  885.      * @throws IndexOutOfBoundsException {@inheritDoc} 
  886.      * @throws IllegalArgumentException {@inheritDoc} 
  887.      */  
  888.     public List<E> subList(int fromIndex, int toIndex) {  
  889.         subListRangeCheck(fromIndex, toIndex, size);            // 合法性检查  
  890.         return new SubList(this0, fromIndex, toIndex);  
  891.     }  
  892.   
  893.     static void subListRangeCheck(int fromIndex, int toIndex, int size) {  
  894.         /* 
  895.          * 越界检查 
  896.          */  
  897.         if (fromIndex < 0)  
  898.             throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);  
  899.         if (toIndex > size)  
  900.             throw new IndexOutOfBoundsException("toIndex = " + toIndex);  
  901.         /*  
  902.          * 非法参数检查 
  903.          */  
  904.         if (fromIndex > toIndex)  
  905.             throw new IllegalArgumentException("fromIndex(" + fromIndex +  
  906.                                                ") > toIndex(" + toIndex + ")");  
  907.     }  
  908.   
  909.     /** 
  910.      * 嵌套内部类:也实现了 RandomAccess,提供快速随机访问特性 
  911.      * @title ArrayList.java  
  912.      * @package com.johnnie.jsca.source  
  913.      * @author johnnie 
  914.      * @time 下午7:50:04 
  915.      * @version v1.0 
  916.      */  
  917.     private class SubList extends AbstractList<E> implements RandomAccess {  
  918.         private final AbstractList<E> parent;  
  919.         private final int parentOffset;                             // 相对于父集合的偏移量,其实就是 fromIndex  
  920.         private final int offset;                                           // 偏移量,默认是 0  
  921.         int size;                                                                   // SubList 存储元素个数  
  922.   
  923.         SubList(AbstractList<E> parent,  
  924.                 int offset, int fromIndex, int toIndex) {  
  925.             // 看到这部分,就理解为什么对 SubList 的操作,会影响父集合---> 因为子集合的处理,仅仅是给出了一个映射到父集合相应区间的引用  
  926.             // 再加上 final,的修饰,就能明白为什么进行了截取子集合操作后,父集合不能删除 SubList 中的首个元素了--->offset 不能更改  
  927.             this.parent = parent;  
  928.             this.parentOffset = fromIndex;  
  929.             this.offset = offset + fromIndex;  
  930.             this.size = toIndex - fromIndex;  
  931.             this.modCount = ArrayList.this.modCount;  
  932.         }  
  933.   
  934.         // 设置新值,返回旧值  
  935.         public E set(int index, E e) {  
  936.             rangeCheck(index);                                                              // 越界检查  
  937.             checkForComodification();  
  938.             E oldValue = ArrayList.this.elementData(offset + index);  
  939.             ArrayList.this.elementData[offset + index] = e;  
  940.             return oldValue;  
  941.         }  
  942.   
  943.         // 取值  
  944.         public E get(int index) {  
  945.             rangeCheck(index);                                                              // 越界检查:设计到 ArrayList 中利用 index 进行访问,就需要进行越界检查  
  946.             checkForComodification();  
  947.             return ArrayList.this.elementData(offset + index);  
  948.         }  
  949.   
  950.         public int size() {  
  951.             checkForComodification();  
  952.             return this.size;  
  953.         }  
  954.   
  955.         // 添加元素  
  956.         public void add(int index, E e) {  
  957.             rangeCheckForAdd(index);  
  958.             checkForComodification();  
  959.             parent.add(parentOffset + index, e);                                        // 对子类添加元素,是直接操作父类添加的  
  960.             this.modCount = parent.modCount;  
  961.             this.size++;  
  962.         }  
  963.   
  964.         // 删除元素  
  965.         public E remove(int index) {  
  966.             rangeCheck(index);  
  967.             checkForComodification();  
  968.             E result = parent.remove(parentOffset + index);                 // 对子类删除元素,是直接操作父类删除的  
  969.             this.modCount = parent.modCount;  
  970.             this.size--;  
  971.             return result;  
  972.         }  
  973.   
  974.         // 范围删除  
  975.         protected void removeRange(int fromIndex, int toIndex) {  
  976.             checkForComodification();  
  977.             parent.removeRange(parentOffset + fromIndex,  
  978.                                parentOffset + toIndex);  
  979.             this.modCount = parent.modCount;  
  980.             this.size -= toIndex - fromIndex;  
  981.         }  
  982.   
  983.         public boolean addAll(Collection<? extends E> c) {  
  984.             return addAll(this.size, c);  
  985.         }  
  986.   
  987.         public boolean addAll(int index, Collection<? extends E> c) {  
  988.             rangeCheckForAdd(index);  
  989.             int cSize = c.size();  
  990.             if (cSize==0)  
  991.                 return false;  
  992.   
  993.             checkForComodification();  
  994.             parent.addAll(parentOffset + index, c);  
  995.             this.modCount = parent.modCount;  
  996.             this.size += cSize;  
  997.             return true;  
  998.         }  
  999.   
  1000.         // SubList 的方法:返回一个迭代器,虽说是返回抽象的 Iterator,但具体实现是 ListIterator  
  1001.         public Iterator<E> iterator() {  
  1002.             return listIterator();  
  1003.         }  
  1004.           
  1005.         // SubList 的方法:返回一个 ListIterator  
  1006.         public ListIterator<E> listIterator(final int index) {  
  1007.             checkForComodification();  
  1008.             rangeCheckForAdd(index);                    // 越界检查,这个地方有点晕,rangeCheckForAdd() 按说只是提供给 Add() 进行越界检查的  
  1009.             final int offset = this.offset;  
  1010.   
  1011.             // 匿名内部类  
  1012.             return new ListIterator<E>() {  
  1013.                 int cursor = index;  
  1014.                 int lastRet = -1;  
  1015.                 int expectedModCount = ArrayList.this.modCount;  
  1016.   
  1017.                 public boolean hasNext() {  
  1018.                     return cursor != SubList.this.size;  
  1019.                 }  
  1020.   
  1021.                 @SuppressWarnings("unchecked")  
  1022.                 public E next() {  
  1023.                     checkForComodification();  
  1024.                     int i = cursor;  
  1025.                     if (i >= SubList.this.size)  
  1026.                         throw new NoSuchElementException();  
  1027.                     Object[] elementData = ArrayList.this.elementData;  
  1028.                     if (offset + i >= elementData.length)  
  1029.                         throw new ConcurrentModificationException();  
  1030.                     cursor = i + 1;  
  1031.                     return (E) elementData[offset + (lastRet = i)];  
  1032.                 }  
  1033.   
  1034.                 public boolean hasPrevious() {  
  1035.                     return cursor != 0;  
  1036.                 }  
  1037.   
  1038.                 @SuppressWarnings("unchecked")  
  1039.                 public E previous() {  
  1040.                     checkForComodification();  
  1041.                     int i = cursor - 1;  
  1042.                     if (i < 0)  
  1043.                         throw new NoSuchElementException();  
  1044.                     Object[] elementData = ArrayList.this.elementData;  
  1045.                     if (offset + i >= elementData.length)  
  1046.                         throw new ConcurrentModificationException();  
  1047.                     cursor = i;  
  1048.                     return (E) elementData[offset + (lastRet = i)];  
  1049.                 }  
  1050.   
  1051.                 @SuppressWarnings("unchecked")  
  1052.                 public void forEachRemaining(Consumer<? super E> consumer) {  
  1053.                     Objects.requireNonNull(consumer);  
  1054.                     final int size = SubList.this.size;  
  1055.                     int i = cursor;  
  1056.                     if (i >= size) {  
  1057.                         return;  
  1058.                     }  
  1059.                     final Object[] elementData = ArrayList.this.elementData;  
  1060.                     if (offset + i >= elementData.length) {  
  1061.                         throw new ConcurrentModificationException();  
  1062.                     }  
  1063.                     while (i != size && modCount == expectedModCount) {  
  1064.                         consumer.accept((E) elementData[offset + (i++)]);  
  1065.                     }  
  1066.                     // update once at end of iteration to reduce heap write traffic  
  1067.                     lastRet = cursor = i;  
  1068.                     checkForComodification();  
  1069.                 }  
  1070.   
  1071.                 public int nextIndex() {  
  1072.                     return cursor;  
  1073.                 }  
  1074.   
  1075.                 public int previousIndex() {  
  1076.                     return cursor - 1;  
  1077.                 }  
  1078.   
  1079.                 public void remove() {  
  1080.                     if (lastRet < 0)  
  1081.                         throw new IllegalStateException();  
  1082.                     checkForComodification();  
  1083.   
  1084.                     try {  
  1085.                         SubList.this.remove(lastRet);  
  1086.                         cursor = lastRet;  
  1087.                         lastRet = -1;  
  1088.                         expectedModCount = ArrayList.this.modCount;  
  1089.                     } catch (IndexOutOfBoundsException ex) {  
  1090.                         throw new ConcurrentModificationException();  
  1091.                     }  
  1092.                 }  
  1093.   
  1094.                 public void set(E e) {  
  1095.                     if (lastRet < 0)  
  1096.                         throw new IllegalStateException();  
  1097.                     checkForComodification();  
  1098.   
  1099.                     try {  
  1100.                         ArrayList.this.set(offset + lastRet, e);  
  1101.                     } catch (IndexOutOfBoundsException ex) {  
  1102.                         throw new ConcurrentModificationException();  
  1103.                     }  
  1104.                 }  
  1105.   
  1106.                 public void add(E e) {  
  1107.                     checkForComodification();  
  1108.   
  1109.                     try {  
  1110.                         int i = cursor;  
  1111.                         SubList.this.add(i, e);  
  1112.                         cursor = i + 1;  
  1113.                         lastRet = -1;  
  1114.                         expectedModCount = ArrayList.this.modCount;  
  1115.                     } catch (IndexOutOfBoundsException ex) {  
  1116.                         throw new ConcurrentModificationException();  
  1117.                     }  
  1118.                 }  
  1119.   
  1120.                 final void checkForComodification() {  
  1121.                     if (expectedModCount != ArrayList.this.modCount)  
  1122.                         throw new ConcurrentModificationException();  
  1123.                 }  
  1124.             };  
  1125.         }  
  1126.   
  1127.         public List<E> subList(int fromIndex, int toIndex) {  
  1128.             subListRangeCheck(fromIndex, toIndex, size);  
  1129.             return new SubList(this, offset, fromIndex, toIndex);  
  1130.         }  
  1131.   
  1132.         private void rangeCheck(int index) {  
  1133.             if (index < 0 || index >= this.size)  
  1134.                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));  
  1135.         }  
  1136.   
  1137.         private void rangeCheckForAdd(int index) {  
  1138.             if (index < 0 || index > this.size)  
  1139.                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));  
  1140.         }  
  1141.   
  1142.         private String outOfBoundsMsg(int index) {  
  1143.             return "Index: "+index+", Size: "+this.size;  
  1144.         }  
  1145.   
  1146.         private void checkForComodification() {  
  1147.             if (ArrayList.this.modCount != this.modCount)  
  1148.                 throw new ConcurrentModificationException();  
  1149.         }  
  1150.   
  1151.         public Spliterator<E> spliterator() {  
  1152.             checkForComodification();  
  1153.             return new ArrayListSpliterator<E>(ArrayList.this, offset,  
  1154.                                                offset + this.size, this.modCount);  
  1155.         }  
  1156.     }  
  1157.     /*------------------------------------- SubList 结束 -------------------------------------------*/  
  1158.       
  1159.     // 同样是 1.8 的方法,用于函数式编程  
  1160.     @Override  
  1161.     public void forEach(Consumer<? super E> action) {  
  1162.         Objects.requireNonNull(action);  
  1163.         final int expectedModCount = modCount;  
  1164.         @SuppressWarnings("unchecked")  
  1165.         final E[] elementData = (E[]) this.elementData;  
  1166.         final int size = this.size;  
  1167.         for (int i=0; modCount == expectedModCount && i < size; i++) {  
  1168.             action.accept(elementData[i]);  
  1169.         }  
  1170.         if (modCount != expectedModCount) {  
  1171.             throw new ConcurrentModificationException();  
  1172.         }  
  1173.     }  
  1174.   
  1175.     /** 
  1176.      * 获取一个分割器 
  1177.      * - fail-fast 
  1178.      * - late-binding:后期绑定 
  1179.      * - java8 开始提供 
  1180.      *  
  1181.      * @return a {@code Spliterator} over the elements in this list 
  1182.      * @since 1.8 
  1183.      */  
  1184.     @Override  
  1185.     public Spliterator<E> spliterator() {  
  1186.         return new ArrayListSpliterator<>(this0, -10);  
  1187.     }  
  1188.   
  1189.     /** Index-based split-by-two, lazily initialized Spliterator */  
  1190.     // 基于索引的、二分的、懒加载的分割器  
  1191.     static final class ArrayListSpliterator<E> implements Spliterator<E> {  
  1192.   
  1193.         private final ArrayList<E> list;  
  1194.         private int index; // current index, modified on advance/split  
  1195.         private int fence; // -1 until used; then one past last index  
  1196.         private int expectedModCount; // initialized when fence set  
  1197.   
  1198.         /** Create new spliterator covering the given  range */  
  1199.         ArrayListSpliterator(ArrayList<E> list, int origin, int fence,  
  1200.                              int expectedModCount) {  
  1201.             this.list = list; // OK if null unless traversed  
  1202.             this.index = origin;  
  1203.             this.fence = fence;  
  1204.             this.expectedModCount = expectedModCount;  
  1205.         }  
  1206.   
  1207.         private int getFence() { // initialize fence to size on first use  
  1208.             int hi; // (a specialized variant appears in method forEach)  
  1209.             ArrayList<E> lst;  
  1210.             if ((hi = fence) < 0) {  
  1211.                 if ((lst = list) == null)  
  1212.                     hi = fence = 0;  
  1213.                 else {  
  1214.                     expectedModCount = lst.modCount;  
  1215.                     hi = fence = lst.size;  
  1216.                 }  
  1217.             }  
  1218.             return hi;  
  1219.         }  
  1220.   
  1221.         public ArrayListSpliterator<E> trySplit() {  
  1222.             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;  
  1223.             return (lo >= mid) ? null : // divide range in half unless too small  
  1224.                 new ArrayListSpliterator<E>(list, lo, index = mid,  
  1225.                                             expectedModCount);  
  1226.         }  
  1227.   
  1228.         public boolean tryAdvance(Consumer<? super E> action) {  
  1229.             if (action == null)  
  1230.                 throw new NullPointerException();  
  1231.             int hi = getFence(), i = index;  
  1232.             if (i < hi) {  
  1233.                 index = i + 1;  
  1234.                 @SuppressWarnings("unchecked") E e = (E)list.elementData[i];  
  1235.                 action.accept(e);  
  1236.                 if (list.modCount != expectedModCount)  
  1237.                     throw new ConcurrentModificationException();  
  1238.                 return true;  
  1239.             }  
  1240.             return false;  
  1241.         }  
  1242.   
  1243.         public void forEachRemaining(Consumer<? super E> action) {  
  1244.             int i, hi, mc; // hoist accesses and checks from loop  
  1245.             ArrayList<E> lst; Object[] a;  
  1246.             if (action == null)  
  1247.                 throw new NullPointerException();  
  1248.             if ((lst = list) != null && (a = lst.elementData) != null) {  
  1249.                 if ((hi = fence) < 0) {  
  1250.                     mc = lst.modCount;  
  1251.                     hi = lst.size;  
  1252.                 }  
  1253.                 else  
  1254.                     mc = expectedModCount;  
  1255.                 if ((i = index) >= 0 && (index = hi) <= a.length) {  
  1256.                     for (; i < hi; ++i) {  
  1257.                         @SuppressWarnings("unchecked") E e = (E) a[i];  
  1258.                         action.accept(e);  
  1259.                     }  
  1260.                     if (lst.modCount == mc)  
  1261.                         return;  
  1262.                 }  
  1263.             }  
  1264.             throw new ConcurrentModificationException();  
  1265.         }  
  1266.   
  1267.         public long estimateSize() {  
  1268.             return (long) (getFence() - index);  
  1269.         }  
  1270.   
  1271.         public int characteristics() {  
  1272.             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;  
  1273.         }  
  1274.     }  
  1275.   
  1276.     @Override  
  1277.     public boolean removeIf(Predicate<? super E> filter) {  
  1278.         Objects.requireNonNull(filter);  
  1279.         // figure out which elements are to be removed  
  1280.         // any exception thrown from the filter predicate at this stage  
  1281.         // will leave the collection unmodified  
  1282.         int removeCount = 0;  
  1283.         final BitSet removeSet = new BitSet(size);  
  1284.         final int expectedModCount = modCount;  
  1285.         final int size = this.size;  
  1286.         for (int i=0; modCount == expectedModCount && i < size; i++) {  
  1287.             @SuppressWarnings("unchecked")  
  1288.             final E element = (E) elementData[i];  
  1289.             if (filter.test(element)) {  
  1290.                 removeSet.set(i);  
  1291.                 removeCount++;  
  1292.             }  
  1293.         }  
  1294.         if (modCount != expectedModCount) {  
  1295.             throw new ConcurrentModificationException();  
  1296.         }  
  1297.   
  1298.         // shift surviving elements left over the spaces left by removed elements  
  1299.         final boolean anyToRemove = removeCount > 0;  
  1300.         if (anyToRemove) {  
  1301.             final int newSize = size - removeCount;  
  1302.             for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {  
  1303.                 i = removeSet.nextClearBit(i);  
  1304.                 elementData[j] = elementData[i];  
  1305.             }  
  1306.             for (int k=newSize; k < size; k++) {  
  1307.                 elementData[k] = null;  // Let gc do its work  
  1308.             }  
  1309.             this.size = newSize;  
  1310.             if (modCount != expectedModCount) {  
  1311.                 throw new ConcurrentModificationException();  
  1312.             }  
  1313.             modCount++;  
  1314.         }  
  1315.   
  1316.         return anyToRemove;  
  1317.     }  
  1318.   
  1319.     @Override  
  1320.     @SuppressWarnings("unchecked")  
  1321.     public void replaceAll(UnaryOperator<E> operator) {  
  1322.         Objects.requireNonNull(operator);  
  1323.         final int expectedModCount = modCount;  
  1324.         final int size = this.size;  
  1325.         for (int i=0; modCount == expectedModCount && i < size; i++) {  
  1326.             elementData[i] = operator.apply((E) elementData[i]);  
  1327.         }  
  1328.         if (modCount != expectedModCount) {  
  1329.             throw new ConcurrentModificationException();  
  1330.         }  
  1331.         modCount++;  
  1332.     }  
  1333.   
  1334.     @Override  
  1335.     @SuppressWarnings("unchecked")  
  1336.     public void sort(Comparator<? super E> c) {  
  1337.         final int expectedModCount = modCount;  
  1338.         Arrays.sort((E[]) elementData, 0, size, c);  
  1339.         if (modCount != expectedModCount) {  
  1340.             throw new ConcurrentModificationException();  
  1341.         }  
  1342.         modCount++;  
  1343.     }  
  1344.       
  1345. }  

2.3 ArrayList 特别注意

在对ArrayList进行分析的过程中,发现 ArrayList 有很多需要仔细考虑的重点。基本上,刚刚的代码里都写上了这些点。但是还是总结一下。如下所示:

(1) ArrayList 基于数组实现,其内存储元素的数组为 elementData

elementData 的声明为:transient Object[] elementData;

(2) ArrayList 中EMPTY_ELEMENTDATA 和 DEFAULTCAPACITY_EMPTY._ELEMENTDATA 的使用

这两个常量,使用场景不同。前者是用在用户通过 ArrayList(int initialCapacity) 该构造方法直接指定初试容量为 0 时,后者是用户直接使用无参构造创建 ArrayList 时。

(3) ArrayList 默认容量为 10。

调用无参构造新建一个 ArrayList 时,其 elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA, 当第一次使用 add() 添加元素时,ArrayList的容量会为 10。
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);  

(4) ArrayList 的扩容计算为 newCapacity = oldCapacity + (oldCapacity >> 1); 且扩容并非是无限制的,有内存限制、虚拟机限制。

(5) ArrayList 的 toArray() 方法和 subList() 方法,在源数据和子数据之间的区别

  • toArray():对该方法返回的数组,进行操作(增删改查)都不会影响源数据(ArrayList中elementData)。二者之间是不会相互影响的
  • subList():对返回的子集合,进行操作(增删改查)都会影响父集合。而且若是对父集合中进行删除操作(仅仅在删除子集合的首个元素)时,会抛出异常 java.util.ConcurrentModificationException

(6) 对 ArrayList 进行操作(如 add()、clear())后,即使 elementData 实际上的长度 > 其内元素个数,但是再直接打印该list时,显示结果还是[x,x,x] (注:x 代表其内实际(或有效)存储的元素)

对于 elementData 中存储情况和直接打印list (即System.out.println(list))结果不一致的原因,是因为 AbstractCollection<E> 中对 toString() 进行了定义。代码如下:
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public String toString() {  
  2.        Iterator<E> it = iterator();  
  3.        if (! it.hasNext())  
  4.            return "[]";  
  5.   
  6.        StringBuilder sb = new StringBuilder();  
  7.        sb.append('[');  
  8.        for (;;) {  
  9.            E e = it.next();  
  10.            sb.append(e == this ? "(this Collection)" : e);  
  11.            if (! it.hasNext())  
  12.                return sb.append(']').toString();  
  13.            sb.append(',').append(' ');  
  14.        }  
  15.    } 
0 0