顺序存储线性表_ArrayList

  相信大家在日常开发过程中 List 应该使用的非常非常多,今天就来简单学习一下 List 的数据结构 顺序存储线性表。

一、什么是顺序存储线性表

  顺序存储线性表是最基本、最简单、也是最常用的一种数据结构。

  线性表中数据元素之间的关系是一对一的关系,即除了第一个和最后一个数据元素之外,其它数据元素都是首尾相接的(注意,这句话只适用大部分线性表,而不是全部。比如,循环链表逻辑层次上也是一种线性表(存储层次上属于链式存储),但是把最后一个数据元素的尾指针指向了首位结点)。

  顺序存储线性表的相邻元素之间存在着序偶关系。如用(a1,…,ai-1,ai,ai+1,…,an)表示一个顺序表,则表中 ai-1 领先于 ai,ai 领先于 ai+1,称 ai-1 是 ai 的直接前驱元素,ai+1 是 ai 的直接后继元素。当 i=1,2,…,n-1 时,ai 有且仅有一个直接后继,当 i=2,3,…,n 时,ai 有且仅有一个直接前驱,n 为线性表的长度,如果 n==0 时,线性表为空表

二、顺序存储线性表的特征

  绝大多数的顺序存储线性表都有一下几个特征:

  ①. 线性表中都会存在唯一的一个 "首元素"。

  ②. 线性表中都会存在唯一的一个"尾元素"。

  ③. 线性表除最后一个元素外都存在"后继"。

  ④. 线性表除第一个元素外都存在"前驱"。

  ⑤. 存储位置连续,可以很方便的计算出各个元素的地址。

  如果每个元素占用的存储单元为 C ,那么:

    Loc(An) = Loc(An-1) + C

    Loc(An) = Loc(A1) + (n - 1)* C

三、JDK源码解读

  在 java 中,ArrayList 是典型的顺序存储线性表,下面来解读一下JDK 1.8 中 ArrayList 源码中的方法,以及父类,接口中的一些方法。

   首先,进入到 ArrayList 中,简单看了一下ArrayList 的继承关系,ArrayList 继承 AbstractList, AbstractList 继承 AbstractCollection 类,实现了 List 接口, AbstractCollection 类实现了 Collection 接口,而 List 继承了 Collection 接口, Collection  继承了 Iterable 接口,下面就依次来简单解读这些接口以及类的实现方法以及作用。

  ArrayList 与它的父类接口的关系图:

  ①. Iterable 接口

    用途:Iterable 接口是 java 中的顶级接口之一,它的作用主要可以使实现类集合使用迭代器去遍历自己的元素。

    方法:

方法名 参数 返回值 描述
Iterator Iterator<T> 返回一个内部元素为 T 的迭代器
                                     forEach                                           Consumer接口                                           void         

Iterable 接口中的默认方法,其中可以传入一个Consumer的接口,可以去遍历内部的每一个元素,并且可以自定义方法,对每一个元素进行操作

spliterator Spliterator<T> Iterable 接口中的默认方法,创建并返回一个分割迭代器
 1 public interface Iterable<T> {
 2     /**
 3      * 获取一个内部为 T 的迭代器
 4      *
 5      * @return 返回一个迭代器.
 6      */
 7     Iterator<T> iterator();
 8 
 9     /**
10      * 被 default 关键字修饰,表示该方法为本接口的默认方法,迭代一个    
11      * 集合并传入一个方法实现来对集合的每一个元素进行操作。
12      */
13     default void forEach(Consumer<? super T> action) {
14         Objects.requireNonNull(action);// 判空操作,如果 action 为 null 则返回,NullPointerExcation();
15         for (T t : this) {
16             action.accept(t);
17         }
18     }
19 
20     /**
21      * 此方法也是该接口的默认方法,获取一个可分割迭代器。
22      */
23     default Spliterator<T> spliterator() {
24         return Spliterators.spliteratorUnknownSize(iterator(), 0);
25     }
26 }

  ②. Collection 接口

    用途:Collection接口是高度抽象出来的集合类接口,其中包含了大多数集合所需要的共同的方法,如增、删、改、查等。

    方法:

方法名 参数 返回值 描述
size int 获取一个集合的元素个数
isEmpty boolean 判断该集合是否为空集合
contains Object o boolean 判断该集合是否包含 o 元素
iterator Iterator<E> 返回一个内部元素为 E 的迭代器
toArray Object[] 将该集合转换为数组
                                toArray                                                       T[] a                                                                     T[]                                                             将集合中的元素转换到指定的数组中,如果指定数组为空,则将集合中的元素放入一个全新的数组中,如果不为空则返回传入的数组,并且传入数组的长度为集合元素的个数
add E e boolean 将元素e加入到集合中
remove Object o boolean 将 o 元素从集合中移除
containsAll Collection<?> c boolean 判断集合 c 是否被该集合包含
addAll Collection<? extends E> c boolean 将集合 c 中的元素都添加到该集合中
removeAll Collection<? extends E> c boolean 将该集合中所有 c 集合中出现的元素移除
removeIf Predicate<? super E> filter boolean Collection 接口中的默认方法,可以按照一定的规则去删除集合中的元素
retainAll Collection<?> c boolean 保留该集合中在 c 集合中存在的元素,其他元素进行移除
clear void 清空集合
equals Object o boolean 用 o 与该集合进行比较
hashCode int 获取该集合的hashCode值
spliterator Spliterator<T> Collection 接口中的默认方法,创建并返回一个分割迭代器
stream Stream<E>

Collection 接口中的默认方法,将该集合转换成Stream串行流

parallelStream   Stream<E>  Collection 接口中的默认方法,将该集合转换成Stream并行流
  1 public interface Collection<E> extends Iterable<E> {
  2     // Query Operations
  3 
  4     /**
  5      * 获取一个集合的元素个数
  6      */
  7     int size();
  8 
  9     /**
 10      * 判断该集合是否为空集合
 11      */
 12     boolean isEmpty();
 13 
 14     /**
 15      * 判断该集合是否包含 o 元素
 16      */
 17     boolean contains(Object o);
 18 
 19     /**
 20      * 返回一个内部元素为 E 的迭代器
 21      */
 22     Iterator<E> iterator();
 23 
 24     /**
 25      * 将该集合转换为数组
 26      */
 27     Object[] toArray();
 28 
 29     /**
 30      *  将集合中的元素转换到指定的数组中,如果指定数组为空,则将集合中的元素放入一个全新的数组中,如果不为空则返回传入的数组,并且传入数组的长度为集合元素的个数
 31      */
 32     <T> T[] toArray(T[] a);
 33 
 34     /**
 35      * 将元素e加入到集合中
 36      */
 37     boolean add(E e);
 38 
 39     /**
 40      * 将 o 元素从集合中移除
 41      */
 42     boolean remove(Object o);
 43 
 44 
 45     /**
 46      * 判断集合 c 是否被该集合包含
 47      */
 48     boolean containsAll(Collection<?> c);
 49 
 50     /**
 51      * 将集合 c 中的元素都添加到该集合中
 52      */
 53     boolean addAll(Collection<? extends E> c);
 54 
 55     /**
 56      * 将该集合中所有 c 集合中出现的元素移除
 57      */
 58     boolean removeAll(Collection<?> c);
 59 
 60     /**
 61      * Collection 接口中的默认方法,可以按照一定的规则去删除集合中的元素
 62      */
 63     default boolean removeIf(Predicate<? super E> filter) {
 64         Objects.requireNonNull(filter);
 65         boolean removed = false;
 66         final Iterator<E> each = iterator();
 67         while (each.hasNext()) {
 68             if (filter.test(each.next())) {
 69                 each.remove();
 70                 removed = true;
 71             }
 72         }
 73         return removed;
 74     }
 75 
 76     /**
 77      * 保留该集合中在 c 集合中存在的元素,其他元素进行移除
 78      */
 79     boolean retainAll(Collection<?> c);
 80 
 81     /**
 82      * 清空集合
 83      */
 84     void clear();
 85 
 86     /**
 87      * 用 o 与该集合进行比较
 88      */
 89     boolean equals(Object o);
 90 
 91     /**
 92      * 获取该集合的hashCode值
 93      */
 94     int hashCode();
 95 
 96     /**
 97      * Collection 接口中的默认方法,创建并返回一个分割迭代器
 98      */
 99     @Override
100     default Spliterator<E> spliterator() {
101         return Spliterators.spliterator(this, 0);
102     }
103 
104     /**
105      * Collection 接口中的默认方法,将该集合转换成Stream串行流
106      */
107     default Stream<E> stream() {
108         return StreamSupport.stream(spliterator(), false);
109     }
110 
111     /**
112      * Collection 接口中的默认方法,将该集合转换成Stream并行流
113      */
114     default Stream<E> parallelStream() {
115         return StreamSupport.stream(spliterator(), true);
116     }
117 }

  ③. List 接口

    用途:List 接口是 Conllection 接口的子接口,它可以定义一个可重复的线性集合,可以在不同的位置存放相同的元素。

    方法 :其中有许多方法与 Conllection接口的方法相同,就不在此一一列出

方法名 参数 返回值 描述
addAll int index, Collection<? extends E> c boolean 在指定位置index处添加集合元素c
replaceAll UnaryOperator<E> operator void List 集合中的默认方法,对集合中的元素进行操作,将执行结果存入元素的位置
sort Comparator<? super E> c void 按照给定的排序规则进行排序
get int index E 返回列表中index位置的元素。
set int index, E element E 将列表中 index 位置的元素替换为 element
add int index, E element void 在列表 index 位置添加元素 element
remove int index E 删除 index 位置的元素
indexOf Object o int 返回 o 元素第一次出现的位置
lastIndexOf Object o int 返回 o 元素最后一次出现的位置
listIterator ListIterator<E> 返回一个 ListIterator 迭代器
subList int fromIndex, int toIndex List<E> 返回集合从 fromIndex 的位置到 toIndex 位置的元素的集合
 1 public interface List<E> extends Collection<E> {
 2 
 3     /**
 4      * 在指定位置index处添加集合元素c
 5      */
 6     boolean addAll(int index, Collection<? extends E> c);
 7 
 8     /**
 9      * 对集合中的元素进行操作,将执行结果存入元素的位置
10      */
11     default void replaceAll(UnaryOperator<E> operator) {
12         Objects.requireNonNull(operator);
13         final ListIterator<E> li = this.listIterator();
14         while (li.hasNext()) {
15             li.set(operator.apply(li.next()));
16         }
17     }
18 
19     /**
20      * 按照给定的排序规则进行排序
21      */
22     @SuppressWarnings({"unchecked", "rawtypes"})
23     default void sort(Comparator<? super E> c) {
24         Object[] a = this.toArray(); //首先将集合转为数组
25         Arrays.sort(a, (Comparator) c); //使用数组排序的sort方法进行排序
26         ListIterator<E> i = this.listIterator();
27         for (Object e : a) { //再将该集合的每个位置进行替换
28             i.next();
29             i.set((E) e);
30         }
31     }
32 
33     /**
34      * 返回列表中 index 位置的元素。
35      */
36     E get(int index);
37 
38     /**
39      * 将列表中 index 位置的元素替换为 element
40      */
41     E set(int index, E element);
42 
43     /**
44      * 在列表 index 位置添加元素 element
45      */
46     void add(int index, E element);
47 
48     /**
49      * 删除 index 位置的元素
50      */
51     E remove(int index);
52 
53     /**
54      * 返回 o 元素第一次出现的位置
55      */
56     int indexOf(Object o);
57 
58     /**
59      * 返回 o 元素最后一次出现的位置
60      */
61     int lastIndexOf(Object o);
62 
63     /**
64      * 返回一个 ListIterator 迭代器
65      */
66     ListIterator<E> listIterator();
67 
68     /**
69      * 返回一个 从 index 开始的 ListIterator 迭代器
70      */
71     ListIterator<E> listIterator(int index);
72 
73     // View
74 
75     /**
76      * 返回集合从 fromIndex 的位置到 toIndex 位置的元素的集合
77      */
78     List<E> subList(int fromIndex, int toIndex);
79 
80 }

   ④. AbstractCollection 抽象类

    用途:这个类是个抽象类,直接实现了Collection接口的方法,其中为 list 和  set 直接或者间接提供了方法实现。

    方法:

方法名 参数 返回值 描述
size int 抽象方法,由子类实现
iterator Iterator<E> 上层的获取迭代器的方法,在这里没有实现,由子类实现
isEmpty boolean  判断集合是否为空
contains Object o boolean  判断 o 对象是否被该集合包含
toArray Object[] 将集合转换为数组
toArray T[] a T[] 将集合转换到传入的数组中
add E e boolean  此类中的add方法,子类必须重写自己的方法,此类不支持单个添加元素
remove Object o boolean  删除 o 元素
containsAll Collection<?> c boolean  判断 c 集合中的元素是否都被该集合包含
addAll Collection<? extends E> c boolean  新增所有元素
removeAll Collection<?> c boolean  删除传入集合的每一个元素
retainAll Collection<?> c boolean  删除除传入集合元素以外的元素
clear void   清空集合
  1 public abstract class MyAbstractCollection<E> implements Collection<E>{
  2     
  3     //指定集合的最大长度为 Integer.MAX_VALUE - 8
  4     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  5     
  6     /**
  7      * 无参构造器
  8      */
  9     public MyAbstractCollection() {}
 10 
 11     /**
 12      * 上层的size方法,在这里没有实现。
 13      */
 14     @Override
 15     public abstract int size();
 16     
 17     /**
 18      * 上层的获取迭代器的方法,在这里没有实现
 19      */
 20     @Override
 21     public abstract Iterator<E> iterator();
 22 
 23     /**
 24      * 判断集合是否为空
 25      */
 26     @Override
 27     public boolean isEmpty() {
 28         return size() == 0;
 29     }
 30 
 31     /**
 32      * 判断 o 对象是否被该集合包含
 33      */
 34     @Override
 35     public boolean contains(Object o) {
 36         Iterator<E> it = iterator(); //获取迭代器
 37         if (o == null) { //如果 o == null 判断集合中是否有 null 元素
 38             while (it.hasNext()) { 
 39                 if (it.next() == null) {
 40                     return true;
 41                 }
 42             }
 43         } else {
 44             while (it.hasNext()) {
 45                 if (it.next().equals(o)) {
 46                     return true;
 47                 }
 48             }
 49         }
 50         return false;
 51     }
 52 
 53     /**
 54      * 将集合转换为数组
 55      */
 56     @Override
 57     public Object[] toArray() {
 58         Object [] r = new Object[size()];
 59         Iterator<E> it = iterator();
 60         for (int i = 0; i < r.length; i++) {
 61             //如果发现迭代器中的值小于 r的长度 则进行缩容
 62             if (!it.hasNext()) {
 63                 return Arrays.copyOf(r, i);
 64             }
 65             r[i] = it.next();
 66         }
 67         //如果发现迭代器中的值大于 r的长度  则进行扩容
 68         return it.hasNext() ? finishToArray(r, it) : r;
 69     }
 70     
 71     /**
 72      * 数组扩容
 73      * @param r 
 74      * @param it
 75      * @return
 76      */
 77     private static <T> T[] finishToArray(T[] r, Iterator<?> it) {
 78         int i = r.length;
 79         while(it.hasNext()) {
 80             int newLeng = r.length; 
 81             //当新长度与原长度相同时进行扩容
 82             if (i == newLeng) {
 83                 //扩容原长度的一半+1
 84                 int cap = newLeng + (newLeng >> 1) + 1;
 85                 //此处要判断cap的值是否大于Integer的最大值
 86                 if (cap - MAX_ARRAY_SIZE > 0) {
 87                     cap = hugeCapacity(cap + 1);
 88                 }
 89                 r = Arrays.copyOf(r, cap);
 90             }
 91             r[i ++] = (T) it.next();
 92         }
 93         //最后判断r的实际长度与 i 是否相等, 如果不等就将后面多余的位置删除
 94         return (r.length == i) ? r : Arrays.copyOf(r, i);
 95     }
 96 
 97     /**
 98      * 如果数组长度超出最大长度的处理
 99      * @param minCapacity
100      * @return
101      */
102     private static int hugeCapacity(int minCapacity) {
103         if (minCapacity < 0) {
104             throw new OutOfMemoryError("数组长度过长");
105         }
106         return minCapacity > MAX_ARRAY_SIZE ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
107     }
108     
109     /**
110      * 将集合转换到传入的数组中
111      */
112     @Override
113     @SuppressWarnings("unchecked")
114     public <T> T[] toArray(T[] a) {
115         int size = size();
116         //如果 a的长度大于或者等于 集合的长度则 r就等于a数组,否则就新建一个数组
117         T[] r = a.length >= size() ? a : (T[]) Array.newInstance(
118                 a.getClass().getComponentType(), size);
119         Iterator<E> it = iterator();
120         
121         for (int i = 0; i < r.length; i++) {
122             if (!it.hasNext()) {
123                 if (a == r) {//如果是r与传入的数组是同一个数组 则将后面的位置 置为 null
124                     r[i] = null;
125                 } else if (a.length < i) { //如果传入的数组长度小于r的长度 则缩容到i的长度
126                     return Arrays.copyOf(r, i);
127                 } else {//如果传入的数组长度大于或等于r的长度  则将后面的位置都置为null
128                     System.arraycopy(r, 0, a, 0, i);
129                     if (a.length > i) {
130                         a[i] = null;
131                     }
132                 }
133                 return a;
134             }
135             r[i] = (T) it.next();
136         }
137         return it.hasNext() ? finishToArray(r, it) : r;
138     }
139 
140     /**
141      * 此类中的add方法,子类必须重写自己的方法,此类不支持单个添加元素
142      */
143     @Override
144     public boolean add(E e) {
145         throw new UnsupportedOperationException();
146     }
147 
148     /**
149      * 删除 o 元素
150      */
151     @Override
152     public boolean remove(Object o) {
153         Iterator<E> it = iterator();
154         if (o == null) { 
155             while (it.hasNext()) { //如果 o 为 null 则将第一个 null元素删除
156                 if (it.next() == null) {
157                     it.remove();
158                     return false;
159                 }
160             }
161         } else {
162             while (it.hasNext()) { //如果 找到第一个 与o元素相同的值 删除
163                 if (o.equals(it.next())) {
164                     it.remove();
165                     return false;
166                 }
167             }
168         }
169         return false;
170     }
171 
172     /**
173      * 判断 c 集合中的元素是否都被该集合包含
174      */
175     @Override
176     public boolean containsAll(Collection<?> c) {
177         //判断 c 中每一个元素是否存在
178         for (Object o : c) { 
179             if (!contains(o)) {
180                 return false;
181             }
182         }
183         return true;
184     }
185     
186     /**
187      * 新增所有元素
188      */
189     @Override
190     public boolean addAll(Collection<? extends E> c) {
191         boolean token = false;
192         for (E o : c) { 
193             if (add(o)) {
194                 token = true;
195             }
196         }
197         return token;
198     }
199 
200     /**
201      * 删除传入集合的每一个元素
202      */
203     @Override
204     public boolean removeAll(Collection<?> c) {
205         Objects.requireNonNull(c);
206         boolean token = false;
207         Iterator<E> it = iterator();
208         //迭代集合本身,判断每一个元素是否存在于集合 c 中,如果存在则删除
209         while (it.hasNext()) {
210             if (c.contains(it.next())) {
211                 it.remove();
212                 token = true;
213             }
214         }
215         return token;
216     }
217 
218     /**
219      * 删除除传入集合元素以外的元素
220      */
221     @Override
222     public boolean retainAll(Collection<?> c) {
223         Objects.requireNonNull(c);
224         boolean token = false;
225         Iterator<E> it = iterator();
226         //迭代集合本身,判断每一个元素是否存在于集合 c 中,如果不存在则删除
227         while (it.hasNext()) {
228             if (!c.contains(it.next())) {
229                 it.remove();
230                 token = true;
231             }
232         }
233         return token;
234     }
235 
236     /**
237      * 清空集合
238      */
239     @Override
240     public void clear() {
241         Iterator<E> it = iterator();
242         //迭代集合删除每一个元素
243         while (it.hasNext()) {
244             it.next();
245             it.remove();
246         }
247     }
248 
249 }

  ⑤. AbstractList 抽象类

    作用:此类继承 AbstractCollection 抽象类,继承 List 接口 ,为 ArrayList 的父类,提供了大部分集合操作的方法。此类中还存在几个内部类 分别是 ListItr,Itr,除了这两个内部类之外,SubList和RandomAccessSubList 这两个类也在 AbstractCollection 中。 ListItr 类 为list定义独有的迭代器,而 Itr 则为 ListItr 的父类。在ListItr 类中主要的一些方法都是去判断指针的位置,去描述指针是如何去移动,如何去删除元素,删除元素后对集合的改变,以及多个迭代器之间的互相的影响。SubList 类为集合提供了截取集合中某一段的方法,但是这个方法存在一些问题,他内部的方法是直接在传入集合上直接进行操作的,也就是说不仅仅会改变截取的部分集合,还会改变传入的集合,所以要谨慎使用。在下面方法中,内部类的方法就不提供了,但是会在后面的代码展示中简单解析一下代码的含义,以及操作的意义。

    方法:

方法名  参数  返回值  描述
add E e boolean 重新父类的add方法,返回boolean值
add int index, E element void

实现 List 接口中的add方法,如果直接调用这个方法会抛出异常
所以在子类中一定要重写此方法

get int index E List 接口中的get方法,在这里不做实现,由子类去实现
set int index, E element E

List 接口中的set方法,在这里只是抛出异常,子类如果直接调用,则会抛出异常,
如果要使用则需要子类去重写这个set方法

remove int index E

List 接口中的remove方法,在这里只是抛出异常,子类如果直接调用,则会抛出异常,
如果要使用则需要子类去重写这个remove方法

addAll int index, Collection<? extends E> c boolean 重写 List 接口中的addAll方法
indexOf Object o int List 接口中的方法, 获取第一个与 o 对象,相同的元素的位置,如果没有则返回 -1
lastIndexOf Object o int List 接口中的方法, 获取最后一个与 o 对象,相同的元素的位置
iterator  无 Iterator<E> 获取迭代器
listIterator  无 ListIterator<E> 获取ListIterator迭代器
listIterator int index ListIterator<E> 获取迭代器从index开始
removeRange int fromIndex, int toIndex void 删除集合fromIndex到toIndex的元素
  1 public abstract class MyAbstractList<E> extends MyAbstractCollection<E> implements List<E>{
  2     
  3     /**
  4      * 构造函数由子类调用
  5      */
  6     protected MyAbstractList() {
  7     }
  8     
  9     /**
 10      * 重新父类的add方法,返回boolean值
 11      */
 12     @Override
 13     public boolean add(E e) {
 14         add(size(), e);
 15         return true;
 16     }
 17     
 18     /**
 19      * 实现 List 接口中的add方法,如果直接调用这个方法会抛出异常
 20      * 所以在子类中一定要重写此方法
 21      */
 22     @Override
 23     public void add(int index, E element) {
 24         throw new UnsupportedOperationException();
 25     }
 26     
 27     /**
 28      * List 接口中的get方法,在这里不做实现,由子类去实现
 29      */
 30     @Override
 31     public abstract E get(int index);
 32 
 33     /**
 34      * List 接口中的set方法,在这里只是抛出异常,子类如果直接调用,则会抛出异常,
 35      * 如果要使用则需要子类去重写这个set方法
 36      */
 37     @Override
 38     public E set(int index, E element) {
 39         throw new UnsupportedOperationException();
 40     }
 41     
 42     /**
 43      * List 接口中的remove方法,在这里只是抛出异常,子类如果直接调用,则会抛出异常,
 44      * 如果要使用则需要子类去重写这个remove方法
 45      */
 46     @Override
 47     public E remove(int index) {
 48         throw new UnsupportedOperationException();
 49     }
 50     
 51     /**
 52      * 此参数为修改的次数,他主要是和迭代器一起使用,来确保线程安全,
 53      * 保证线程之间的修改可见性。如果出现线程不安全的情况导致这个值与迭代器中的modCount值不同时则会抛出异常。
 54      * 在一个迭代器初始的时候会赋予它调用这个迭代器的对象的mCount,如何在迭代器遍历的过程中,
 55      * 一旦发现这个对象的mcount和迭代器中存储的mcount不一样那就抛异常 
 56      */
 57     protected transient int modCount = 0;
 58     
 59     /**
 60      * 重写 List 接口中的addAll方法
 61      */
 62     @Override
 63     public boolean addAll(int index, Collection<? extends E> c) {
 64         //判断数组是否越界,如果越界抛出下标越界异常
 65         rangeCheckForAdd(index);
 66         boolean token = false;
 67         for (E e : c) {
 68             add(index++, e);
 69             token = true;
 70         }
 71         return token;
 72     }
 73 
 74     /**
 75      * 判断传入的index是否在小于0 或者大于集合长度
 76      * @param index
 77      */
 78     private void rangeCheckForAdd(int index) {
 79         if (index < 0 || index > size())
 80             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 81     }
 82     
 83     /**
 84      * 获取下标的位置,和实际集合长度
 85      * @param index
 86      * @return
 87      */
 88     private String outOfBoundsMsg(int index) {
 89         return "Index: "+index+", Size: "+size();
 90     }
 91     
 92     /**
 93      * List 接口中的方法, 获取第一个与 o 对象,相同的元素的位置,如果没有则返回 -1
 94      */
 95     @Override
 96     public int indexOf(Object o) {
 97         ListIterator<E> it = listIterator();
 98         if (o == null) {
 99             while(it.hasNext()) {
100                 if (it.next() == null) {
101                     //获取目前迭代器的位置
102                     return it.previousIndex();
103                 }
104             }
105         } else {
106             while(it.hasNext()) {
107                 if (it.next().equals(o)) {
108                     //获取目前迭代器上一个元素的位置
109                     return it.previousIndex();
110                 }
111             }
112         }
113         return -1;
114     }
115 
116     /**
117      * List 接口中的方法, 获取最后一个与 o 对象,相同的元素的位置
118      */
119     @Override
120     public int lastIndexOf(Object o) {
121         ListIterator<E> it = listIterator(size());
122         if (o == null) {
123             //获取迭代器是否存在的上一个元素,如果存在返回true
124             while (it.hasPrevious()) {
125                 //获取迭代器上一个元素,反向迭代
126                 if (it.previous() == null) {
127                     //返回迭代器下一个元素的位置
128                     return it.nextIndex();
129                 }
130             }
131         } else {
132             while (it.hasPrevious()) {
133                 //获取迭代器上一个元素,反向迭代
134                 if (o.equals(it.previous())) {
135                     //返回迭代器下一个元素的位置
136                     return it.nextIndex();
137                 }
138             }
139         }
140         return -1;
141     }
142     
143     /**
144      * 获取迭代器
145      */
146     @Override
147     public Iterator<E> iterator() {
148         return new Itr();
149     }
150 
151     /**
152      * 获取ListIterator迭代器
153      */
154     @Override
155     public ListIterator<E> listIterator() {
156         return listIterator(0);
157     }
158 
159     /**
160      * 获取迭代器从index开始
161      */
162     @Override
163     public ListIterator<E> listIterator(int index) {
164         rangeCheckForAdd(index);
165         return new ListItr(index);
166     }
167 
168     /**
169      * 删除集合fromIndex到toIndex的元素
170      * @param fromIndex
171      * @param toIndex
172      */
173     protected void removeRange(int fromIndex, int toIndex) {
174        ListIterator<E> it = listIterator(fromIndex);
175        for (int i = 0; i < toIndex - fromIndex; i++) {
176            it.next();
177            it.remove();
178        }
179     }
180 
181     private class Itr implements Iterator<E> {
182         
183         /**
184          * 调用迭代器 next 方法返回的索引
185          */
186         int cursor = 0;
187 
188         /**
189          * 上一次调用next 方法返回的索引
190          */
191         int lastRet = -1;
192 
193         /**
194          * 此参数为迭代器中的结构修改的次数,初始化时会将集合中的 modCount 赋值给迭代器
195          */
196         int expectedModCount = modCount;
197 
198         /**
199          * 判断是否存在下一个元素
200          */
201         @Override
202         public boolean hasNext() {
203             return cursor != size();
204         }
205 
206         @Override
207         public E next() {
208             //确保其他线程没有操作此集合
209             checkForComodification();
210             try {
211                 //获取下一次next的元素的下标
212                 int i = cursor;
213                 //获取该下标的元素
214                 E e = get(i);
215                 //将此下标赋值给lastRet
216                 lastRet = cursor;
217                 //获取下一次next的元素下标
218                 cursor ++;
219                 return e;
220             } catch (Exception e) {
221                 checkForComodification();
222                 throw new NoSuchElementException();
223             }
224         }
225         
226         /**
227          * 此处还重写了Iterator接口的remove方法
228          */
229         @Override
230         public void remove() {
231             //如果lastRet的值小于0则说明迭代器指针还处于集合最前面,则没有删除的元素,所以抛出异常
232             if(lastRet < 0) {
233                 throw new IllegalStateException();
234             }
235             //确保其他线程没有操作此集合
236             checkForComodification();
237             try {
238                 //删除上一个元素
239                 MyAbstractList.this.remove(lastRet);
240                 if (lastRet < cursor) {
241                     cursor --;
242                 }
243                 //删除只会删除next跳过的那个元素,删除一次之后将上一个下标置为-1,保证不能多次删除
244                 lastRet = -1;
245                 expectedModCount = modCount;
246             } catch (Exception e) {
247                 throw new ConcurrentModificationException();
248             }
249         }
250 
251         /**
252          * 使用此方法去保证线程之间的操作可见性,如果迭代器的操作次数与集合的操作次数不一致,则会抛出异常
253          */
254         final void checkForComodification() {
255             if (modCount != expectedModCount)
256                 throw new ConcurrentModificationException();
257         }
258     }
259     
260     private class ListItr extends Itr implements ListIterator<E> {
261 
262         ListItr(int index) {
263             cursor = index;
264         }
265         
266         /**
267          * 判断上一个元素是否存在
268          */
269         @Override
270         public boolean hasPrevious() {
271             //如果cursor为0则表示指针在集合头部,则上一个元素不存在
272             return cursor != 0;
273         }
274         
275         /**
276          * 获取上一个元素
277          */
278         @Override
279         public E previous() {
280             //判断是否被其他线程修改集合结构
281             checkForComodification();
282             try {
283                 //获取上一个元素的下标
284                 int i = cursor - 1;
285                 //获取上一个元素
286                 E e = get(i);
287                 cursor = i;
288                 lastRet = i;
289                 return e;
290             } catch (Exception e) {
291                 checkForComodification();
292                 throw new NoSuchElementException();
293             }
294         }
295 
296         /**
297          * 获取下一个元素的下标
298          */
299         @Override
300         public int nextIndex() {
301             return cursor;
302         }
303 
304         /**
305          * 获取上一个元素的下标
306          */
307         @Override
308         public int previousIndex() {
309             return cursor - 1;
310         }
311 
312         /**
313          * 修改元素
314          */
315         @Override
316         public void set(E e) {
317             //修改元素修改的为上一次跳过的元素,如果上一次的元素是-1则说明还在集合头部,
318             //无元素可以修改,所以抛出异常
319             if (lastRet < 0) {
320                 throw new IllegalStateException();
321             }
322             checkForComodification();
323             try {
324                 //使用MyAbstractList类的set方法
325                 MyAbstractList.this.set(lastRet, e);
326                 //将修改的次数赋值给迭代器
327                 expectedModCount = modCount;
328             } catch (Exception e2) {
329                 throw new ConcurrentModificationException();
330             }
331         }
332 
333         /**
334          * 新增元素
335          */
336         @Override
337         public void add(E e) {
338             checkForComodification();
339             try {
340                 //获取集合下一个元素的位置
341                 int i = cursor;
342                 //将元素新增到下一个位置
343                 MyAbstractList.this.add(i, e);
344                 lastRet = -1;
345                 cursor++;
346                 expectedModCount = modCount;
347             } catch (Exception e2) {
348                 throw new ConcurrentModificationException();
349             }
350         }
351         
352     }
353 }
354 
355 class SubList<E> extends MyAbstractList<E> {
356 
357     //原始的集合
358     private final MyAbstractList<E> l;
359     //开始截取集合的起始位置
360     private final int offset;
361     //截取集合的长度
362     private int size;
363     
364     SubList(MyAbstractList<E> list, int fromIndex, int toIndex){
365         //如果起始位置小于0 则抛出异常
366         if (fromIndex < 0) {
367             throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
368         }
369         //如果结束位置大于数组长度 则抛出异常
370         if (toIndex > list.size()) {
371             throw new IndexOutOfBoundsException("toIndex = " + toIndex);
372         }
373         //如果起始位置大于结束位置 则抛出异常
374         if (fromIndex > toIndex) {
375             throw new IllegalArgumentException("fromIndex(" + fromIndex +
376                     ") > toIndex(" + toIndex + ")");
377         }
378         l = list;
379         offset = fromIndex;
380         size = toIndex - fromIndex;
381         this.modCount = l.modCount;
382     }
383     
384     /**
385      * 获取index的元素
386      */
387     @Override
388     public E get(int index) {
389         //判断集合下标是否不在集合范围内
390         rangeCheck(index);
391         checkForComodification();
392         //这里为什么要加offset呢,因为此处的l为原始的list 
393         //而offset 为截取后的开始位置,然后加上现在要获取的元素的下标位置,
394         //才是现在要获取的元素
395         return l.get(index + offset);
396     }
397     
398     /**
399      * 修改index位置的元素
400      */
401     @Override
402     public E set(int index, E element) {
403         rangeCheck(index);
404         checkForComodification();
405         return l.set(index+offset, element);
406     }
407     
408     /**
409      * 判断集合结构是否被其他线程改变
410      */
411     private void checkForComodification() {
412         if (this.modCount != l.modCount)
413             throw new ConcurrentModificationException();
414     }
415     
416     /**
417      * 判断集合下标是否不在集合范围内
418      * @param index
419      */
420     private void rangeCheck(int index) {
421         if (index < 0 || index >= size)
422             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
423     }
424     
425     /**
426      * 输出集合下标和长度
427      * @param index
428      * @return
429      */
430     private String outOfBoundsMsg(int index) {
431         return "Index: " + index + ", Size: " + size;
432     }
433 
434     /**
435      * 获取截取后集合的长度
436      */
437     @Override
438     public int size() {
439         checkForComodification();
440         return size;
441     }
442     
443     /**
444      * 在指定位置添加元素
445      */
446     @Override
447     public void add(int index, E element) {
448         rangeCheck(index);
449         checkForComodification();
450         l.add(index + offset, element);
451         this.modCount = l.modCount;
452         size++;
453     }
454     
455     /**
456      * 删除指定位置元素
457      */
458     @Override
459     public E remove(int index) {
460         rangeCheck(index);
461         checkForComodification();
462         E e = l.remove(index + offset);
463         this.modCount = l.modCount;
464         size--;
465         return e;
466     }
467     
468     /**
469      * 删除指定区域的元素
470      */
471     @Override
472     protected void removeRange(int fromIndex, int toIndex) {
473         checkForComodification();
474         l.removeRange(fromIndex + offset, toIndex + offset);
475         this.modCount = l.modCount;
476         size -= (toIndex - fromIndex);
477     }
478     
479     /**
480      * 添加c到集合中,从size开始
481      */
482     @Override
483     public boolean addAll(Collection<? extends E> c) {
484         return addAll(size, c);
485     }
486     
487     /**
488      * 添加c到集合中,从index开始
489      */
490     @Override
491     public boolean addAll(int index, Collection<? extends E> c) {
492         rangeCheck(index);
493         int cSize = c.size();
494         if (c.size() == 0) {
495             return false;
496         }
497         checkForComodification();
498         l.addAll(index + offset, c);
499         size += cSize;
500         return true;
501     }
502     
503     /**
504      * 获取迭代器
505      */
506     public Iterator<E> iterator() {
507         return listIterator();
508     }
509     
510     /**
511      * 获取ListIterator
512      */
513     public ListIterator<E> listIterator(final int index) {
514         checkForComodification();
515         rangeCheckForAdd(index);
516         return new ListIterator<E>() {
517 
518             private final ListIterator<E> i = l.listIterator(index+offset);
519 
520             public boolean hasNext() {
521                 return nextIndex() < size;
522             }
523 
524             public E next() {
525                 if (hasNext())
526                     return i.next();
527                 else
528                     throw new NoSuchElementException();
529             }
530 
531             public boolean hasPrevious() {
532                 return previousIndex() >= 0;
533             }
534 
535             public E previous() {
536                 if (hasPrevious())
537                     return i.previous();
538                 else
539                     throw new NoSuchElementException();
540             }
541 
542             public int nextIndex() {
543                 return i.nextIndex() - offset;
544             }
545 
546             public int previousIndex() {
547                 return i.previousIndex() - offset;
548             }
549 
550             public void remove() {
551                 i.remove();
552                 SubList.this.modCount = l.modCount;
553                 size--;
554             }
555 
556             public void set(E e) {
557                 i.set(e);
558             }
559 
560             public void add(E e) {
561                 i.add(e);
562                 SubList.this.modCount = l.modCount;
563                 size++;
564             }
565         };
566     }
567     
568      private void rangeCheckForAdd(int index) {
569          if (index < 0 || index > size)
570             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
571      }
572      
573      /**
574       * 截取集合
575       */
576      @Override
577      public List<E> subList(int fromIndex, int toIndex) {
578             return new SubList<>(this, fromIndex, toIndex);
579         }
580 }
581 
582 class RandomAccessSubList<E> extends SubList<E> implements RandomAccess {
583     RandomAccessSubList(MyAbstractList<E> list, int fromIndex, int toIndex) {
584         super(list, fromIndex, toIndex);
585     }
586 
587     public List<E> subList(int fromIndex, int toIndex) {
588         return new RandomAccessSubList<>(this, fromIndex, toIndex);
589     }
590 }

  ⑥. ArrayList  

    作用:ArrayList,是我们在开发过程中最常使用到的线性表的结构,它的内部可以存放重复的元素,并且可以存放null元素,属于线程不安全的集合类,查询效率高。

    方法:在java8中在arrayList中加入了一些方法,还加入了获取流的类,在这里我只列出A让rayList中的方法,其他一些内部类就不一一列出,但是在下面源码解读中,我会将每个方法自己的注释以注解的方式进行注释。

方法名 入参 出参 描述
trimToSize void 去除集合中预留元素的位置
ensureCapacity int minCapacity void 数组扩容
size int 获取集合长度
isEmpty boolean 判断集合是否为空
contains Object o boolean 判断集合是否包含 o
indexOf Object o int 获取o第一次出现的下标
lastIndexOf Object o int 获取o最后一次出现在集合的位置
clone Object 克隆集合
toArray Object[] 将集合转数组
toArray T[] a T[] 将集合转为传入的数组
elementData int index E 获取第 index个元素
get int index E 获取第index个元素
rangeCheck int index void 判断传入的下标是否比数组长度大
outOfBoundsMsg int index String 获取传入的index的长度和数组长度
set int index, E element E 修改index元素,将新的element放入集合index的位置,并返回oldelement
add E e boolean 新增元素
add int index, E element void 在指定位置插入元素
rangeCheckForAdd int index void 判断index是否在集合长度范围内
remove int index E 删除index的元素 ,并返回
remove Object o boolean 删除第一个元素 o
fastRemove int index void 删除 index 位置的元素
clear void 清空集合
addAll Collection<? extends E> c boolean 将c集合添加到本集合
addAll int index, Collection<? extends E> c boolean 在index处,添加集合c
removeRange int fromIndex, int toIndex void 删除fromIndex到toIndex的元素
removeAll Collection<?> c boolean 删除集合中包含c集合中的元素
writeObject java.io.ObjectOutputStream s void 用于MyArrayList序列化使用
readObject java.io.ObjectInputStream s void 反序列化方法
listIterator int index ListIterator<E> 获取从 index 开始的List迭代器
listIterator ListIterator<E> 获取从 0 开始的List迭代器
iterator Iterator<E> 获取迭代器
subList int fromIndex, int toIndex List<E> 截取集合 从fromIndex 到 toIndex
forEach Consumer<? super E> action void 遍历集合,其中每个元素执行action中的方法
spliterator Spliterator<E> 获取Spliterator迭代器 java8提供
removeIf Predicate<? super E> filter boolean 如果集合中元素在一定条件内就删除,条件由开发者传入
replaceAll UnaryOperator<E> operator void 按照一定的规则对集合进行操作,规则由开发者传入
sort Comparator<? super E> c void java8中新加入的方法,按照一定的规则进行排序
   1 public class MyArrayList<E> extends AbstractList<E>
   2 implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
   3 
   4     private static final long serialVersionUID = 2572016039206533046L;
   5 
   6     /**
   7      * 创建集合时的初始 长度
   8      */
   9     private static final int DEFAULT_CAPACITY = 10;
  10 
  11     /**
  12      * 当创建集合时传入的长度为0时默认使用下面的数组
  13      */
  14     private static final Object[] EMPTY_ELEMENTDATA = {};
  15 
  16     /**
  17      * 当创建集合时不传入参数时默认使用下面的数组
  18      */
  19     private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  20     
  21     /**
  22      * 集合最大长度
  23      */
  24     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  25 
  26     /**
  27      * 这个为集合默认使用的数组,使用 transient 修饰,将并不会被序列化到指定位置
  28      */
  29     transient Object[] elementData; 
  30 
  31     /**
  32      * elementData 数组长度
  33      */
  34     private int size;
  35     
  36     /**
  37      * 记录数组结构变化次数,保证多线程对数组结构改变时线程安全
  38      */
  39     protected transient int modCount = 0;
  40     
  41     /**
  42      * 无参构造器
  43      */
  44     public MyArrayList() {
  45         //直接使用默认的数组
  46         this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  47     }
  48     
  49     /**
  50      * 第一个有参构造器,传入集合长度
  51      * @param initialCapacity 创建集合的长度
  52      */
  53     public MyArrayList(int initialCapacity) {
  54         if (initialCapacity > 0) { 
  55             //如果长度大于 0 则创建对应长度的数组,并且赋值给elementData
  56             this.elementData = new Object[initialCapacity];
  57         } else if (initialCapacity == 0) {
  58             //如果长度等于 0 则直接使用默认数组 EMPTY_ELEMENTDATA
  59             this.elementData = EMPTY_ELEMENTDATA;
  60         } else {
  61             //如果小于 0 则抛出异常
  62             throw new IllegalArgumentException("Illegal Capacity: "+
  63                     initialCapacity);
  64         }
  65         
  66     }
  67 
  68     /**
  69      * 第二个有参构造器,传入一个集合
  70      * @param c 
  71      */
  72     public MyArrayList(Collection<? extends E> c) {
  73         //将 传入的集合转为数组
  74         elementData = c.toArray();
  75         //获取集合长度
  76         size = elementData.length;
  77         if (size != 0) {
  78             //如果传入的集合转数组之后不是Object的数组,则copy 到Object 数组中
  79             if (elementData.getClass() != Object[].class) {
  80                 elementData = Arrays.copyOf(elementData, size, Object[].class);    
  81             }
  82         } else {
  83             //如果传入的集合长度为 0 则使用默认的数组 EMPTY_ELEMENTDATA
  84             elementData = EMPTY_ELEMENTDATA;
  85         }
  86     }
  87     
  88     /**
  89      * 去除集合中预留元素的位置
  90      */
  91     public void trimToSize() {
  92         modCount ++;
  93         if (size < elementData.length) {
  94             //如果size与数组长度不相等,则判断size是否为0 如果为0 则使用默认数组
  95             //如果size不为0则将elementDta中size长度之后的预留元素的位置删除
  96             elementData = (size == 0) ?
  97                     EMPTY_ELEMENTDATA :
  98                         Arrays.copyOf(elementData, size);
  99         }
 100     }
 101     
 102     /**
 103      * 数组扩容
 104      * @param minCapacity 扩容的长度
 105      */
 106     public void ensureCapacity(int minCapacity) {
 107         //判断elementData 是否为默认的数组,如果是最小长度为 0 否则 最小长度为默认的10
 108         int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
 109                 ? 0 : DEFAULT_CAPACITY;
 110         //判断扩容的长度是否比最小长度大,如果大继续扩容,否则不扩容
 111         if (minCapacity > minExpand) {
 112             ensureExplicitCapacity(minCapacity);
 113         }
 114     }
 115     
 116     private void ensureCapacityInternal(int minCapacity) {
 117         /**
 118          * 判断elementData 是否为默认数组,如果是则 minCapacity 与
 119          * 默认长度做比较,取较大的那个数扩容
 120          */
 121         if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
 122             minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
 123         }
 124         //否则按照传入值进行扩容
 125         ensureExplicitCapacity(minCapacity);
 126     }
 127 
 128     private void ensureExplicitCapacity(int minCapacity) {
 129         modCount++;
 130 
 131         // 传入值与现在数组长度做比较,如果传入值大于目前数组长度继续扩容
 132         if (minCapacity - elementData.length > 0)
 133             grow(minCapacity);
 134     }
 135 
 136     private void grow(int minCapacity) {
 137         // 获取数组原长度
 138         int oldCapacity = elementData.length;
 139         // 数组新长度为原长度+原长度的一半
 140         int newCapacity = oldCapacity + (oldCapacity >> 1);
 141         //如果新长度小于传入的minCapacity 则新长度 = minCapacity
 142         if (newCapacity - minCapacity < 0)
 143             newCapacity = minCapacity;
 144         //如果新长度大于集合最大长度则执行hugeCapacity 获取扩容的长度
 145         if (newCapacity - MAX_ARRAY_SIZE > 0)
 146             newCapacity = hugeCapacity(minCapacity);
 147         // 进行扩容
 148         elementData = Arrays.copyOf(elementData, newCapacity);
 149     }
 150     
 151     private static int hugeCapacity(int minCapacity) {
 152         if (minCapacity < 0) // overflow
 153             throw new OutOfMemoryError();
 154         //如果新长度大于集合最大长度则返回 int的最大值,否则返回集合最大值
 155         return (minCapacity > MAX_ARRAY_SIZE) ?
 156             Integer.MAX_VALUE :
 157             MAX_ARRAY_SIZE;
 158     }
 159     
 160     /**
 161      * 获取集合长度
 162      */
 163     @Override
 164     public int size() {
 165         return size;
 166     }
 167     
 168     /**
 169      * 判断集合是否为空
 170      */
 171     @Override
 172     public boolean isEmpty() {
 173         return size == 0;
 174     }
 175     
 176     /**
 177      * 判断集合是否包含 o
 178      */
 179     @Override
 180     public boolean contains(Object o) {
 181         //如果集合中可以获取到o的下标,则说明o存在于集合中
 182         return indexOf(o) >= 0;
 183     }
 184     
 185     /**
 186      * 获取o第一次出现的下标
 187      */
 188     @Override
 189     public int indexOf(Object o) {
 190         if (o == null) {
 191             for (int i = 0; i < size; i++)
 192                 if (elementData[i]==null)
 193                     return i;
 194         } else {
 195             for (int i = 0; i < size; i++)
 196                 if (o.equals(elementData[i]))
 197                     return i;
 198         }
 199         return -1;
 200     }
 201     
 202     /**
 203      * 获取o最后一次出现在集合的位置
 204      */
 205     @Override
 206     public int lastIndexOf(Object o) {
 207         if (o == null) {
 208             for (int i = size-1; i >= 0; i--)
 209                 if (elementData[i]==null)
 210                     return i;
 211         } else {
 212             for (int i = size-1; i >= 0; i--)
 213                 if (o.equals(elementData[i]))
 214                     return i;
 215         }
 216         return -1;
 217     }
 218     
 219     /**
 220      * 克隆集合
 221      */
 222     @Override
 223     public Object clone() {
 224         try {
 225             MyArrayList<?> v = (MyArrayList<?>) super.clone();
 226             //copy原集合,并将结构改变次数置为0
 227             v.elementData = Arrays.copyOf(elementData, size);
 228             v.modCount = 0;
 229             return v;
 230         } catch (CloneNotSupportedException e) {
 231             throw new InternalError(e);
 232         }
 233     }
 234     
 235     /**
 236      * 将集合转数组
 237      */
 238     @Override
 239     public Object[] toArray() {
 240         return Arrays.copyOf(elementData, size);
 241     }
 242     
 243     /**
 244      * 将集合转为传入的数组
 245      */
 246     @Override
 247     public <T> T[] toArray(T[] a) {
 248         if (a.length < size)
 249             // 如果传入的数组长度小于集合的长度,则需要先扩容再copy
 250             return (T[]) Arrays.copyOf(elementData, size, a.getClass());
 251         System.arraycopy(elementData, 0, a, 0, size);
 252         if (a.length > size)
 253             a[size] = null;
 254         return a;
 255     }
 256     
 257     /**
 258      * 获取第 index个元素
 259      * @param index
 260      * @return
 261      */
 262     E elementData(int index) {
 263         return (E) elementData[index];
 264     }
 265     
 266     /**
 267      * 获取第index个元素
 268      */
 269     @Override
 270     public E get(int index) {
 271         rangeCheck(index);
 272         return elementData(index);
 273     }
 274 
 275     /**
 276      * 判断传入的下标是否比数组长度大
 277      * @param index
 278      */
 279     private void rangeCheck(int index) {
 280         if (index >= size)
 281             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 282     }
 283     
 284     /**
 285      * 获取传入的index的长度和数组长度
 286      * @param index
 287      * @return
 288      */
 289     private String outOfBoundsMsg(int index) {
 290         return "Index: "+index+", Size: "+size;
 291     }
 292     
 293     /**
 294      * 修改index元素,将新的element放入集合index的位置,并返回oldelement
 295      */
 296     @Override
 297     public E set(int index, E element) {
 298         rangeCheck(index);
 299 
 300         E oldValue = elementData(index);
 301         elementData[index] = element;
 302         return oldValue;
 303     }
 304 
 305     /**
 306      * 新增元素
 307      */
 308     @Override
 309     public boolean add(E e) {
 310         //数组扩容,在内部会判断数组是否需要扩容,如果长度不足则扩容,否则不扩容
 311         ensureCapacityInternal(size + 1); 
 312         elementData[size++] = e;
 313         return true;
 314     }
 315 
 316     /**
 317      * 在指定位置插入元素
 318      */
 319     @Override
 320     public void add(int index, E element) {
 321         //判断index是否在集合长度范围内
 322         rangeCheckForAdd(index);
 323         //判断是否需要扩容
 324         ensureCapacityInternal(size + 1); 
 325         //将index以及后面的元素向后移动一位
 326         System.arraycopy(elementData, index, elementData, index + 1,
 327                          size - index);
 328         //简化element 放在 index的位置上
 329         elementData[index] = element;
 330         size++;
 331     }
 332 
 333     /**
 334      * 判断index是否在集合长度范围内
 335      * @param index
 336      */
 337     private void rangeCheckForAdd(int index) {
 338         if (index > size || index < 0)
 339             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 340     }
 341     
 342     /**
 343      * 删除index的元素 ,并返回
 344      */
 345     @Override
 346     public E remove(int index) {
 347         rangeCheck(index);
 348 
 349         modCount++;
 350         E oldValue = elementData(index);
 351 
 352         //index 位置后面元素的个数
 353         int numMoved = size - index - 1;
 354         //如果index 后面存在元素,则向前移动一位
 355         if (numMoved > 0)
 356             System.arraycopy(elementData, index+1, elementData, index,
 357                              numMoved);
 358         //将最后一位置为null
 359         elementData[--size] = null; 
 360 
 361         return oldValue;
 362     }
 363     
 364     /**
 365      * 删除第一个元素 o
 366      */
 367     @Override
 368     public boolean remove(Object o) {
 369         if (o == null) {
 370             for (int index = 0; index < size; index++)
 371                 if (elementData[index] == null) {
 372                     //删除第一个 o元素
 373                     fastRemove(index);
 374                     return true;
 375                 }
 376         } else {
 377             for (int index = 0; index < size; index++)
 378                 if (o.equals(elementData[index])) {
 379                     fastRemove(index);
 380                     return true;
 381                 }
 382         }
 383         return false;
 384     }
 385     
 386     /**
 387      * 删除 index 位置的元素
 388      * @param index
 389      */
 390     private void fastRemove(int index) {
 391         modCount++;
 392         //index 位置后面元素的个数
 393         int numMoved = size - index - 1;
 394         //如果index 后面存在元素,则向前移动一位
 395         if (numMoved > 0)
 396             System.arraycopy(elementData, index+1, elementData, index,
 397                              numMoved);
 398         //将最后一位置为null
 399         elementData[--size] = null; 
 400     }
 401     
 402     /**
 403      * 清空集合
 404      */
 405     @Override
 406     public void clear() {
 407         modCount++;
 408 
 409         // 将每一个元素置null
 410         for (int i = 0; i < size; i++)
 411             elementData[i] = null;
 412 
 413         size = 0;
 414     }
 415     
 416     /**
 417      * 将c集合添加到本集合
 418      */
 419     @Override
 420     public boolean addAll(Collection<? extends E> c) {
 421         //转数组
 422         Object[] a = c.toArray();
 423         int numNew = a.length;
 424         //扩容 
 425         ensureCapacityInternal(size + numNew);  
 426         //copy数组,将a数组从0开始copy到 elementData,从size开始,copy numNew个元素
 427         System.arraycopy(a, 0, elementData, size, numNew);
 428         //修改长度
 429         size += numNew;
 430         return numNew != 0;
 431     }
 432     
 433     /**
 434      * 在index处,添加集合c
 435      */
 436     @Override
 437     public boolean addAll(int index, Collection<? extends E> c) {
 438         //判断index是否超出集合范围
 439         rangeCheckForAdd(index);
 440 
 441         Object[] a = c.toArray();
 442         int numNew = a.length;
 443         //数组扩容
 444         ensureCapacityInternal(size + numNew);  
 445 
 446         int numMoved = size - index;
 447         if (numMoved > 0)
 448             //将index后面的元素向后移动 c 集合中元素个数个长度
 449             System.arraycopy(elementData, index, elementData, index + numNew,
 450                              numMoved);
 451         //将a集合中的元素从0开始复制到elementData的index位置
 452         System.arraycopy(a, 0, elementData, index, numNew);
 453         //修改长度
 454         size += numNew;
 455         return numNew != 0;
 456     }
 457     
 458     /**
 459      * 删除fromIndex到toIndex的元素
 460      */
 461     @Override
 462     protected void removeRange(int fromIndex, int toIndex) {
 463         modCount++;
 464         int numMoved = size - toIndex;
 465         //将elementData 从 toIndex开始的元素 移动到fromIndex的位置,移动 numMoved个元素
 466         System.arraycopy(elementData, toIndex, elementData, fromIndex,
 467                          numMoved);
 468 
 469         int newSize = size - (toIndex-fromIndex);
 470         //将后面移动的元素的位置置为null
 471         for (int i = newSize; i < size; i++) {
 472             elementData[i] = null;
 473         }
 474         size = newSize;
 475     }
 476     
 477     /**
 478      * 删除集合中包含c集合中的元素
 479      */
 480     @Override
 481     public boolean removeAll(Collection<?> c) {
 482         //判断c是否为null
 483         Objects.requireNonNull(c);
 484         return batchRemove(c, false);
 485     }
 486     
 487     
 488     private boolean batchRemove(Collection<?> c, boolean complement) {
 489         final Object[] elementData = this.elementData;
 490         int r = 0, w = 0;
 491         boolean modified = false;
 492         try {
 493             for (; r < size; r++)
 494                 //w为下一个不重复元素的下标,r为目前遍历的元素下标,将不重复的元素放到w位置
 495                 if (c.contains(elementData[r]) == complement)
 496                     elementData[w++] = elementData[r];
 497         } finally {
 498             //如果上面的循环没有结束,则将没有遍历完的元素向前移动
 499             if (r != size) {
 500                 System.arraycopy(elementData, r,
 501                                  elementData, w,
 502                                  size - r);
 503                 w += size - r;
 504             }
 505             //将w后面的元素全部置为null
 506             if (w != size) {
 507                 for (int i = w; i < size; i++)
 508                     elementData[i] = null;
 509                 modCount += size - w;
 510                 //长度修改为w
 511                 size = w;
 512                 modified = true;
 513             }
 514         }
 515         return modified;
 516     }
 517     
 518     /**
 519      * 用于MyArrayList序列化使用
 520      * @param s
 521      * @throws java.io.IOException
 522      */
 523     private void writeObject(java.io.ObjectOutputStream s)
 524             throws java.io.IOException{
 525         // 首先先将非 transient 的进行序列化
 526         int expectedModCount = modCount;
 527         s.defaultWriteObject();
 528 
 529         // 再将集合的长度序列化
 530         s.writeInt(size);
 531 
 532         // 最后将,集合中非 null的进行序列化。我们知道集合初始化有10个长度,也许只用用几个,
 533         //那么这时序列化全部的话就会把后面没有使用的地址的null也序列化进去,这里序列化时,
 534         //调用此方法就会只序列化有值的区域,从而增加序列化效率,剪小序列化后的文件
 535         for (int i=0; i<size; i++) {
 536             s.writeObject(elementData[i]);
 537         }
 538         //如何在序列化过程中集合结构被其他线程修改,则序列化失败
 539         if (modCount != expectedModCount) {
 540             throw new ConcurrentModificationException();
 541         }
 542     }
 543     
 544     /**
 545      * 反序列化方法
 546      * @param s
 547      * @throws java.io.IOException
 548      * @throws ClassNotFoundException
 549      */
 550     private void readObject(java.io.ObjectInputStream s)
 551             throws java.io.IOException, ClassNotFoundException {
 552         elementData = EMPTY_ELEMENTDATA;
 553 
 554         // 首先将非transient 修饰的进行反序列化
 555         s.defaultReadObject();
 556         s.readInt(); 
 557 
 558         if (size > 0) {
 559             // 数组扩容
 560             ensureCapacityInternal(size);
 561 
 562             Object[] a = elementData;
 563             // 解析size个 元素进行反序列化
 564             for (int i=0; i<size; i++) {
 565                 a[i] = s.readObject();
 566             }
 567         }
 568     }
 569     
 570     /**
 571      * 获取从 index 开始的List迭代器
 572      */
 573     public ListIterator<E> listIterator(int index) {
 574         if (index < 0 || index > size)
 575             throw new IndexOutOfBoundsException("Index: "+index);
 576         return new ListItr(index);
 577     }
 578 
 579     /**
 580      * 获取从 0 开始的List迭代器
 581      */
 582     public ListIterator<E> listIterator() {
 583         return new ListItr(0);
 584     }
 585 
 586     /**
 587      * 获取迭代器
 588      */
 589     public Iterator<E> iterator() {
 590         return new Itr();
 591     }
 592     
 593     
 594     private class Itr implements Iterator<E> {
 595         
 596         int cursor;       // 迭代器指针指向的下一个元素的下标
 597         int lastRet = -1; // 迭代器指针跳过的上一个元素的下标,-1表示没有
 598         int expectedModCount = modCount;
 599 
 600         @Override
 601         public boolean hasNext() {
 602             return cursor != size;
 603         }
 604 
 605         @Override
 606         public E next() {
 607             //判断集合结构修改次数是否与迭代器修改次数相同
 608             checkForComodification();
 609             int i = cursor;
 610             if (i > size) {
 611                 throw new NoSuchElementException();
 612             }
 613             Object [] elementData = MyArrayList.this.elementData;
 614             if (i > elementData.length) {
 615                 throw new ConcurrentModificationException();
 616             }
 617             return null;
 618         }
 619         
 620         /**
 621          * 删除指针跳过的元素
 622          */
 623         public void remove() {
 624             if (lastRet < 0) {
 625                 throw new IllegalStateException();
 626             }
 627             checkForComodification();
 628             try {
 629                 //使用arrayList的删除方法
 630                 MyArrayList.this.remove(lastRet);
 631                 cursor = lastRet;
 632                 lastRet = -1;
 633                 expectedModCount = modCount;
 634             } catch (IndexOutOfBoundsException e) {
 635                 throw new ConcurrentModificationException();
 636             }
 637         }
 638         
 639         /**
 640          * java8新加入的方法,迭代集合,并自定义方法执行,但是这里需要注意的是,迭代的集合是从指针的下一个元素开始
 641          * 并不一定是从集合的开始执行,所以请谨慎使用
 642          */
 643         @SuppressWarnings("unchecked")
 644         public void forEachRemaining(Consumer<? super E> consumer) {
 645             //判断传入的方法是否为null
 646             Objects.requireNonNull(consumer);
 647             final int size = MyArrayList.this.size;
 648             int i = cursor;
 649             //指针在最后的位置
 650             if (i > size) {
 651                 return;
 652             }
 653             final Object [] elementData = MyArrayList.this.elementData;
 654             if (i >= elementData.length) {
 655                 throw new ConcurrentModificationException();
 656             }
 657             while(i != size && modCount == expectedModCount) {
 658                 consumer.accept((E)elementData[i++]);
 659             }
 660             cursor = i;
 661             lastRet = i - 1;
 662             checkForComodification();
 663         }
 664         
 665         /**
 666          * 判断集合结构修改次数是否与迭代器修改次数相同
 667          */
 668         final void checkForComodification() {
 669             if (modCount != expectedModCount)
 670                 throw new ConcurrentModificationException();
 671         }
 672         
 673     }
 674     
 675     /**
 676      * list 的迭代器
 677      *
 678      */
 679     private class ListItr extends Itr implements ListIterator<E> {
 680         
 681         ListItr(int index) {
 682             super();
 683             cursor = index;
 684         }
 685 
 686         /**
 687          * 是否存在上一个元素
 688          */
 689         public boolean hasPrevious() {
 690             return cursor != 0;
 691         }
 692 
 693         /**
 694          * 获取下一个元素的下标
 695          */
 696         public int nextIndex() {
 697             return cursor;
 698         }
 699 
 700         /**
 701          * 获取上一个元素的下标
 702          */
 703         public int previousIndex() {
 704             return cursor - 1;
 705         }
 706 
 707         /**
 708          * 获取上一个元素
 709          */
 710         @SuppressWarnings("unchecked")
 711         public E previous() {
 712             checkForComodification();
 713             int i = cursor - 1;
 714             //如果上一个元素下标小于0,说明不存在上一个元素
 715             if (i < 0)
 716                 throw new NoSuchElementException();
 717             Object[] elementData = MyArrayList.this.elementData;
 718             //如果上一个元素下标大于数组的长度,则抛出异常
 719             if (i >= elementData.length)
 720                 throw new ConcurrentModificationException();
 721             cursor = i;
 722             return (E) elementData[lastRet = i];
 723         }
 724         
 725         /**
 726          * 修改指针刚跳过的元素
 727          */
 728         public void set(E e) {
 729             //如果lastRet小于0 则说明没有跳过任何一个元素
 730             if (lastRet < 0)
 731                 throw new IllegalStateException();
 732             checkForComodification();
 733 
 734             try {
 735                 MyArrayList.this.set(lastRet, e);
 736             } catch (IndexOutOfBoundsException ex) {
 737                 throw new ConcurrentModificationException();
 738             }
 739         }
 740 
 741         /**
 742          * 在指针后加入元素
 743          */
 744         public void add(E e) {
 745             checkForComodification();
 746             try {
 747                 int i = cursor;
 748                 MyArrayList.this.add(i, e);
 749                 cursor = i + 1;
 750                 lastRet = -1;
 751                 expectedModCount = modCount;
 752             } catch (IndexOutOfBoundsException ex) {
 753                 throw new ConcurrentModificationException();
 754             }
 755         }
 756     }
 757     
 758     /**
 759      * 截取集合 从fromIndex 到 toIndex
 760      */
 761     public List<E> subList(int fromIndex, int toIndex) {
 762         subListRangeCheck(fromIndex, toIndex, size);
 763         return new SubList(this, 0, fromIndex, toIndex);
 764     }
 765 
 766     /**
 767      * 判断截取集合的位置是否正确
 768      * @param fromIndex
 769      * @param toIndex
 770      * @param size
 771      */
 772     static void subListRangeCheck(int fromIndex, int toIndex, int size) {
 773         if (fromIndex < 0)
 774             throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
 775         if (toIndex > size)
 776             throw new IndexOutOfBoundsException("toIndex = " + toIndex);
 777         if (fromIndex > toIndex)
 778             throw new IllegalArgumentException("fromIndex(" + fromIndex +
 779                                                ") > toIndex(" + toIndex + ")");
 780     }
 781     
 782     
 783     private class SubList extends AbstractList<E> implements RandomAccess {
 784         private final AbstractList<E> parent; //原集合
 785         private final int parentOffset; //开始位置
 786         private final int offset; //结束位置
 787         int size; //需要截取的元素的个数
 788 
 789         SubList(AbstractList<E> parent,
 790                 int offset, int fromIndex, int toIndex) {
 791             this.parent = parent;
 792             this.parentOffset = fromIndex;
 793             this.offset = offset + fromIndex;
 794             this.size = toIndex - fromIndex;
 795             this.modCount = MyArrayList.this.modCount;
 796         }
 797 
 798         /**
 799          * 修改index元素
 800          */
 801         public E set(int index, E e) {
 802             //判断index是否不在集合范围内
 803             rangeCheck(index);
 804             checkForComodification();
 805             //获取原来index位置的元素
 806             E oldValue = MyArrayList.this.elementData(offset + index);
 807             //使用e 替代原来位置的元素
 808             MyArrayList.this.elementData[offset + index] = e;
 809             return oldValue;
 810         }
 811 
 812         /**
 813          * index位置的元素
 814          */
 815         public E get(int index) {
 816             rangeCheck(index);
 817             checkForComodification();
 818             return MyArrayList.this.elementData(offset + index);
 819         }
 820 
 821         /**
 822          * 获取截取后元素的长度
 823          */
 824         public int size() {
 825             checkForComodification();
 826             return this.size;
 827         }
 828 
 829         /**
 830          * 截取后集合中新增元素,因为是在截取前的集合中直接操作,所以谨慎使用
 831          */
 832         public void add(int index, E e) {
 833             rangeCheckForAdd(index);
 834             checkForComodification();
 835             parent.add(parentOffset + index, e);
 836             this.modCount = parent.modCount;
 837             this.size++;
 838         }
 839 
 840         /**
 841          * 删除元素
 842          */
 843         public E remove(int index) {
 844             rangeCheck(index);
 845             checkForComodification();
 846             E result = parent.remove(parentOffset + index);
 847             this.modCount = parent.modCount;
 848             this.size--;
 849             return result;
 850         }
 851 
 852         /**
 853          * 删除从fromIndex开始到toIndex位置的元素
 854          */
 855         protected void removeRange(int fromIndex, int toIndex) {
 856             checkForComodification();
 857             parent.removeRange(parentOffset + fromIndex,
 858                                parentOffset + toIndex);
 859             this.modCount = parent.modCount;
 860             this.size -= toIndex - fromIndex;
 861         }
 862 
 863         /**
 864          * 新增传入集合的所有元素
 865          */
 866         public boolean addAll(Collection<? extends E> c) {
 867             return addAll(this.size, c);
 868         }
 869 
 870         /**
 871          * 在index位置后加入集合c中所有元素
 872          */
 873         public boolean addAll(int index, Collection<? extends E> c) {
 874             rangeCheckForAdd(index);
 875             int cSize = c.size();
 876             if (cSize==0)
 877                 return false;
 878 
 879             checkForComodification();
 880             parent.addAll(parentOffset + index, c);
 881             this.modCount = parent.modCount;
 882             this.size += cSize;
 883             return true;
 884         }
 885 
 886         /**
 887          * 获取迭代器
 888          */
 889         public Iterator<E> iterator() {
 890             return listIterator();
 891         }
 892 
 893         /**
 894          * 获取ListIterator迭代器
 895          */
 896         public ListIterator<E> listIterator(final int index) {
 897             checkForComodification();
 898             rangeCheckForAdd(index);
 899             final int offset = this.offset;
 900 
 901             return new ListIterator<E>() {
 902                 int cursor = index;
 903                 int lastRet = -1;
 904                 int expectedModCount = MyArrayList.this.modCount;
 905 
 906                 /**
 907                  * 判断是否存在下一个元素
 908                  */
 909                 public boolean hasNext() {
 910                     return cursor != SubList.this.size;
 911                 }
 912 
 913                 /**
 914                  * 获取下一个元素
 915                  */
 916                 @SuppressWarnings("unchecked")
 917                 public E next() {
 918                     checkForComodification();
 919                     int i = cursor;
 920                     if (i >= SubList.this.size)
 921                         throw new NoSuchElementException();
 922                     Object[] elementData = MyArrayList.this.elementData;
 923                     if (offset + i >= elementData.length)
 924                         throw new ConcurrentModificationException();
 925                     cursor = i + 1;
 926                     return (E) elementData[offset + (lastRet = i)];
 927                 }
 928 
 929                 /**
 930                  * 判断是否存在上一个元素
 931                  */
 932                 public boolean hasPrevious() {
 933                     return cursor != 0;
 934                 }
 935 
 936                 /**
 937                  * 获取上一个元素
 938                  */
 939                 @SuppressWarnings("unchecked")
 940                 public E previous() {
 941                     checkForComodification();
 942                     int i = cursor - 1;
 943                     if (i < 0)
 944                         throw new NoSuchElementException();
 945                     Object[] elementData = MyArrayList.this.elementData;
 946                     if (offset + i >= elementData.length)
 947                         throw new ConcurrentModificationException();
 948                     cursor = i;
 949                     return (E) elementData[offset + (lastRet = i)];
 950                 }
 951 
 952                 /**
 953                  * 循环遍历指针后面的元素,并执行consumer的方法
 954                  */
 955                 @SuppressWarnings("unchecked")
 956                 public void forEachRemaining(Consumer<? super E> consumer) {
 957                     Objects.requireNonNull(consumer);
 958                     final int size = SubList.this.size;
 959                     int i = cursor;
 960                     if (i >= size) {
 961                         return;
 962                     }
 963                     final Object[] elementData = MyArrayList.this.elementData;
 964                     if (offset + i >= elementData.length) {
 965                         throw new ConcurrentModificationException();
 966                     }
 967                     while (i != size && modCount == expectedModCount) {
 968                         consumer.accept((E) elementData[offset + (i++)]);
 969                     }
 970                     lastRet = cursor = i;
 971                     checkForComodification();
 972                 }
 973 
 974                 /**
 975                  * 获取下一个元素
 976                  */
 977                 public int nextIndex() {
 978                     return cursor;
 979                 }
 980 
 981                 /**
 982                  * 获取上一个元素
 983                  */
 984                 public int previousIndex() {
 985                     return cursor - 1;
 986                 }
 987 
 988                 /**
 989                  * 删除元素
 990                  */
 991                 public void remove() {
 992                     if (lastRet < 0)
 993                         throw new IllegalStateException();
 994                     checkForComodification();
 995 
 996                     try {
 997                         SubList.this.remove(lastRet);
 998                         cursor = lastRet;
 999                         lastRet = -1;
1000                         expectedModCount = MyArrayList.this.modCount;
1001                     } catch (IndexOutOfBoundsException ex) {
1002                         throw new ConcurrentModificationException();
1003                     }
1004                 }
1005 
1006                 /**
1007                  * 修改元素
1008                  */
1009                 public void set(E e) {
1010                     if (lastRet < 0)
1011                         throw new IllegalStateException();
1012                     checkForComodification();
1013 
1014                     try {
1015                         MyArrayList.this.set(offset + lastRet, e);
1016                     } catch (IndexOutOfBoundsException ex) {
1017                         throw new ConcurrentModificationException();
1018                     }
1019                 }
1020 
1021                 /**
1022                  * 新增元素
1023                  */
1024                 public void add(E e) {
1025                     checkForComodification();
1026 
1027                     try {
1028                         int i = cursor;
1029                         SubList.this.add(i, e);
1030                         cursor = i + 1;
1031                         lastRet = -1;
1032                         expectedModCount = MyArrayList.this.modCount;
1033                     } catch (IndexOutOfBoundsException ex) {
1034                         throw new ConcurrentModificationException();
1035                     }
1036                 }
1037 
1038                 final void checkForComodification() {
1039                     if (expectedModCount != MyArrayList.this.modCount)
1040                         throw new ConcurrentModificationException();
1041                 }
1042             };
1043         }
1044 
1045         /**
1046          * 截取集合从fromIndex到toIndex
1047          */
1048         public List<E> subList(int fromIndex, int toIndex) {
1049             subListRangeCheck(fromIndex, toIndex, size);
1050             return new SubList(this, offset, fromIndex, toIndex);
1051         }
1052 
1053         private void rangeCheck(int index) {
1054             if (index < 0 || index >= this.size)
1055                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1056         }
1057 
1058         private void rangeCheckForAdd(int index) {
1059             if (index < 0 || index > this.size)
1060                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1061         }
1062 
1063         private String outOfBoundsMsg(int index) {
1064             return "Index: "+index+", Size: "+this.size;
1065         }
1066 
1067         private void checkForComodification() {
1068             if (MyArrayList.this.modCount != this.modCount)
1069                 throw new ConcurrentModificationException();
1070         }
1071 
1072         public Spliterator<E> spliterator() {
1073             checkForComodification();
1074             return new ArrayListSpliterator<E>(MyArrayList.this, offset,
1075                                                offset + this.size, this.modCount);
1076         }
1077     }
1078     
1079     /**
1080      * 遍历集合,其中每个元素执行action中的方法
1081      */
1082     @Override
1083     public void forEach(Consumer<? super E> action) {
1084         Objects.requireNonNull(action);
1085         final int expectedModCount = modCount;
1086         @SuppressWarnings("unchecked")
1087         final E[] elementData = (E[]) this.elementData;
1088         final int size = this.size;
1089         for (int i=0; modCount == expectedModCount && i < size; i++) {
1090             action.accept(elementData[i]);
1091         }
1092         if (modCount != expectedModCount) {
1093             throw new ConcurrentModificationException();
1094         }
1095     }
1096 
1097     /**
1098      * 获取Spliterator迭代器 java8提供
1099      */
1100     @Override
1101     public Spliterator<E> spliterator() {
1102         return new ArrayListSpliterator<>(this, 0, -1, 0);
1103     }
1104 
1105     static final class ArrayListSpliterator<E> implements Spliterator<E> {
1106 
1107 
1108         private final MyArrayList<E> list; //集合
1109         private int index; //起始位置
1110         private int fence; //结束位置 -1表示最后
1111         private int expectedModCount; //结构改变次数
1112 
1113        
1114         ArrayListSpliterator(MyArrayList<E> list, int origin, int fence,
1115                              int expectedModCount) {
1116             this.list = list; 
1117             this.index = origin;
1118             this.fence = fence;
1119             this.expectedModCount = expectedModCount;
1120         }
1121 
1122         /**
1123          * 获取结束位置
1124          * @return
1125          */
1126         private int getFence() { 
1127             int hi; 
1128             MyArrayList<E> lst;
1129             //如果fence = -1则说明已经到达最后位置
1130             if ((hi = fence) < 0) {
1131                 //如果集合为null则最后位置为0
1132                 if ((lst = list) == null)
1133                     hi = fence = 0;
1134                 else {
1135                     //否则返回集合长度
1136                     expectedModCount = lst.modCount;
1137                     hi = fence = lst.size;
1138                 }
1139             }
1140             return hi;
1141         }
1142 
1143         /**
1144          * 分割迭代器,每调用一次,将原来的迭代器等分为两份,并返回索引靠前的那一个子迭代器。
1145          */
1146         public ArrayListSpliterator<E> trySplit() {
1147             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1148             return (lo >= mid) ? null : 
1149                 new ArrayListSpliterator<E>(list, lo, index = mid,
1150                                             expectedModCount);
1151         }
1152 
1153         /**
1154          * 获取下一个元素并执行action方法
1155          */
1156         public boolean tryAdvance(Consumer<? super E> action) {
1157             if (action == null)
1158                 throw new NullPointerException();
1159             int hi = getFence(), i = index;
1160             //如果开始位置小于结束
1161             if (i < hi) {
1162                 index = i + 1;
1163                 //则获取下一个元素
1164                 @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
1165                 //执行action的方法
1166                 action.accept(e);
1167                 if (list.modCount != expectedModCount)
1168                     throw new ConcurrentModificationException();
1169                 return true;
1170             }
1171             return false;
1172         }
1173 
1174         /**
1175          * 循环执行action方法
1176          */
1177         public void forEachRemaining(Consumer<? super E> action) {
1178             int i, hi, mc; 
1179             MyArrayList<E> lst; Object[] a;
1180             if (action == null)
1181                 throw new NullPointerException();
1182             if ((lst = list) != null && (a = lst.elementData) != null) {
1183                 if ((hi = fence) < 0) {
1184                     mc = lst.modCount;
1185                     hi = lst.size;
1186                 }
1187                 else
1188                     mc = expectedModCount;
1189                 if ((i = index) >= 0 && (index = hi) <= a.length) {
1190                     for (; i < hi; ++i) {
1191                         @SuppressWarnings("unchecked") E e = (E) a[i];
1192                         action.accept(e);
1193                     }
1194                     if (lst.modCount == mc)
1195                         return;
1196                 }
1197             }
1198             throw new ConcurrentModificationException();
1199         }
1200 
1201         public long estimateSize() {
1202             return (long) (getFence() - index);
1203         }
1204 
1205         public int characteristics() {
1206             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1207         }
1208     }
1209 
1210     /**
1211      * 如果集合中元素在一定条件内就删除,条件由开发者传入
1212      */
1213     @Override
1214     public boolean removeIf(Predicate<? super E> filter) {
1215         Objects.requireNonNull(filter);
1216         int removeCount = 0;
1217         //创建一个size长度的BitSet
1218         final BitSet removeSet = new BitSet(size);
1219         final int expectedModCount = modCount;
1220         final int size = this.size;
1221         for (int i=0; modCount == expectedModCount && i < size; i++) {
1222             @SuppressWarnings("unchecked")
1223             final E element = (E) elementData[i];
1224             if (filter.test(element)) {
1225                 //将removeSet的 i 位置 设置为true
1226                 removeSet.set(i);
1227                 removeCount++;
1228             }
1229         }
1230         if (modCount != expectedModCount) {
1231             throw new ConcurrentModificationException();
1232         }
1233         //判读是否有元素需要被删除
1234         final boolean anyToRemove = removeCount > 0;
1235         if (anyToRemove) {
1236             //获取删除元素后 数组的长度
1237             final int newSize = size - removeCount;
1238             for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
1239                 //获取removeSet中i后面第一个为false的元素下标,
1240                 i = removeSet.nextClearBit(i);
1241                 elementData[j] = elementData[i];
1242             }
1243             //将删除结束后,新数组长度后面的元素全部置为null、
1244             for (int k=newSize; k < size; k++) {
1245                 elementData[k] = null;  
1246             }
1247             this.size = newSize;
1248             if (modCount != expectedModCount) {
1249                 throw new ConcurrentModificationException();
1250             }
1251             modCount++;
1252         }
1253 
1254         return anyToRemove;
1255     }
1256 
1257     /**
1258      * 按照一定的规则对集合进行操作,规则由开发者传入
1259      */
1260     @Override
1261     @SuppressWarnings("unchecked")
1262     public void replaceAll(UnaryOperator<E> operator) {
1263         Objects.requireNonNull(operator);
1264         final int expectedModCount = modCount;
1265         final int size = this.size;
1266         //循环遍历每一个元素,并执行规则
1267         for (int i=0; modCount == expectedModCount && i < size; i++) {
1268             elementData[i] = operator.apply((E) elementData[i]);
1269         }
1270         if (modCount != expectedModCount) {
1271             throw new ConcurrentModificationException();
1272         }
1273         modCount++;
1274     }
1275 
1276     /**
1277      * java8中新加入的方法,按照一定的规则进行排序
1278      */
1279     @Override
1280     @SuppressWarnings("unchecked")
1281     public void sort(Comparator<? super E> c) {
1282         final int expectedModCount = modCount;
1283         //调用arrays的方法传入数组,从0开始size个元素,按照c的规则进行排序 
1284         Arrays.sort((E[]) elementData, 0, size, c);
1285         if (modCount != expectedModCount) {
1286             throw new ConcurrentModificationException();
1287         }
1288         modCount++;
1289     }
1290 
1291 }

   以上就是我在学习线性表时的一些感悟以及对ArrayList以及相关的一些接口,父类的源码的解读,其中代码中的注释均是我自己在读源码过程中的理解。如过有地方理解的和大家理解的不一样,还请提出来一起探讨。

-------------------- END ---------------------

 

最后附上作者的微信公众号地址和博客地址 

公众号:wuyouxin_gzh

 

Herrt灬凌夜:https://www.cnblogs.com/wuyx/

版权说明:欢迎以任何方式进行转载,但请在转载后注明出处!

原文地址:https://www.cnblogs.com/wuyx/p/9351964.html