3.Java集合框架剖析 之 ArrayList源码剖析

时间:2022-01-08 14:59:33
   1 package java.util;
   2 
   3 import java.util.function.Consumer;
   4 import java.util.function.Predicate;
   5 import java.util.function.UnaryOperator;
   6 import sun.misc.SharedSecrets;
   7 
   8 public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
   9 {
  10     private static final long serialVersionUID = 8683452581122892189L;
  11 
  12     //默认初始化大小
  13     private static final int DEFAULT_CAPACITY = 10;
  14 
  15     //空数组,当调用无参构造方法的时候,默认给一个空数组,所有实例共享的一个静态属性,当初始化容量为0的时候,就使用这个属性作为实例底层数组
  16     private static final Object[] EMPTY_ELEMENTDATA = {};
  17 
  18     //构造一个空的对象数组,用来与EMPTY_ELEMENTDATA这个数组进行对比,
  19     //来确定当第一次向ArrayList中添加数据时,应该如果进行扩容,就是增加多大的容量
  20     private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  21 
  22     //真正保存数据的数组,所以说ArrayList是用数组来实现的
  23     transient Object[] elementData;
  24 
  25     //实际元素的个数
  26     private int size;
  27 
  28     //设置数组大小的构造方法
  29     //当大于0的时候,就实例化一个initialCapacity的数组
  30     //当等于0的时候,就将静态空数组EMPTY_ELEMENTDATA赋值给elementData,注意:EMPTY_ELEMENTDATA的length为0,不是为空!
  31     //当小于0的时候,抛出异常
  32     public ArrayList(int initialCapacity) {
  33         if (initialCapacity > 0) {
  34         //此处注意:initialCapacity没有赋值给size。size是统计元素的个数,而initialCapacity是实例化数组的大小
  35             this.elementData = new Object[initialCapacity];
  36         } else if (initialCapacity == 0) {
  37             this.elementData = EMPTY_ELEMENTDATA;
  38         } else {
  39             throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
  40         }
  41     }
  42 
  43     //无参构造方法,将静态的空数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA赋值给elementData
  44     //用此无参构造方法构造ArraList的时候,并不会真正产生实例化的数组,而是引用一个静态的空数组
  45     public ArrayList() {
  46         this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  47     }
  48 
  49     // 传递一个集合给ArrayList,
  50         先将集合转换成数组赋值给elementData之后,再判断数组长度,
  51             若等于0,则将EMPTY_ELEMENTDATA赋值给elementData
  52             如果不等于0,还需要判断接受过来的数组(elementData)是否为Object[]类型。
  53             如果不是,将它转换成Object[]类型
  54             根据注释,toArray方法有可能得到的不是Object[]类型
  55     public ArrayList(Collection<? extends E> c) {
  56         elementData = c.toArray();
  57         if ((size = elementData.length) != 0) {
  58             // c.toArray might (incorrectly) not return Object[] (see 6260652)
  59             if (elementData.getClass() != Object[].class)
  60                 elementData = Arrays.copyOf(elementData, size, Object[].class);
  61         } else {
  62             this.elementData = EMPTY_ELEMENTDATA;
  63         }
  64     }
  65 
  66     //将数组尾部多余的删掉,形成新数组,而新数组的length和size相当,节约空间。中间产生的空间开销,JVM会自动回收
  67     public void trimToSize() {
  68         modCount++;
  69         if (size < elementData.length) {
  70             elementData = (size == 0)? EMPTY_ELEMENTDATA : Arrays.copyOf(elementData, size);
  71         }
  72     }
  73 
  74     // 作用:判断当前是否需要进行扩容。提供给外界的方法,使用者可以通过这个方法自己去扩容
  75     // 首先判断elementData是不是空数组,如果是,minExpand=10,如果不是,minExpand=0
  76     // 再判断minExpand跟指定的最小容量minCapacity比较大小,看是否需要进行扩容
  77     public void ensureCapacity(int minCapacity) {
  78         //minExpand:最小扩容数量
  79         int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) ? 0 : DEFAULT_CAPACITY;
  80         if (minCapacity > minExpand) {
  81             ensureExplicitCapacity(minCapacity);
  82         }
  83     }
  84 
  85     // 私有方法,保证minCapacity在容量大小范围内
  86     private static int calculateCapacity(Object[] elementData, int minCapacity) {
  87         if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  88             return Math.max(DEFAULT_CAPACITY, minCapacity);
  89         }
  90         return minCapacity;
  91     }
  92 
  93     // 私有方法,保证minCapacity在容量大小范围内,看是否有必要去扩容
  94     private void ensureCapacityInternal(int minCapacity) {
  95         ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
  96     }
  97 
  98     //私有方法,当最小容量大于数组的长度时,就进行扩容
  99     private void ensureExplicitCapacity(int minCapacity) {
 100         modCount++;
 101         if (minCapacity - elementData.length > 0)
 102             grow(minCapacity);
 103     }
 104 
 105 
 106 
 107     //扩容
 108     private void grow(int minCapacity) {
 109         //获取当前数组的容量
 110         int oldCapacity = elementData.length;
 111         //在当前数组容量的大小情况下,扩容50%
 112         int newCapacity = oldCapacity + (oldCapacity >> 1);
 113         //当扩容后的容量大小 还是小于最小容量,新的数组容量就采用最小容量的长度
 114         if (newCapacity - minCapacity < 0)
 115             newCapacity = minCapacity;
 116         //处理新数组容量大于MAX_ARRAY_SIZE
 117         if (newCapacity - MAX_ARRAY_SIZE > 0)
 118             newCapacity = hugeCapacity(minCapacity);
 119         //调用系统的copyOf方法,先开辟一个newCapacity的数组,然后把之前的旧数组的数据复制到新数组
 120         elementData = Arrays.copyOf(elementData, newCapacity);
 121     }
 122     
 123     //数组所能开辟的最大长度。因为有些虚拟机保留了一些header words在数组中,尝试要开辟更大的长度的数组,可能会出现OutOfMemoryError异常
 124     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 125     
 126     //求出最大的容量值,先判断minCapacity是否小于0,溢出就抛出OutOfMemoryError异常
 127     //否则就去判断minCapacity 是否大于 MAX_ARRAY_SIZE,是,返回 Integer.MAX_VALUE ,否, 返回MAX_ARRAY_SIZE
 128     private static int hugeCapacity(int minCapacity) {
 129         if (minCapacity < 0)
 130             throw new OutOfMemoryError();
 131         return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
 132     }
 133     
 134 
 135     
 136     //真正保存的数据个数
 137     public int size() {
 138         return size;
 139     }
 140 
 141     //判断数据个数是否为空
 142     public boolean isEmpty() {
 143         return size == 0;
 144     }
 145 
 146     //判断是否包含某个元素
 147     public boolean contains(Object o) {
 148         return indexOf(o) >= 0;
 149     }
 150 
 151     // indexOf是来获得指定元素(包括null)在容器中的位置的,位置从0开始到size-1结束,如果返回-1表示不包含
 152     // 对于重复的元素,只获取第一个所在的位置
 153     public int indexOf(Object o) {
 154         if (o == null) {
 155             for (int i = 0; i < size; i++)
 156                 if (elementData[i]==null)
 157                     return i;
 158         } else {
 159             for (int i = 0; i < size; i++)
 160                 if (o.equals(elementData[i]))
 161                     return i;
 162         }
 163         return -1;
 164     }
 165 
 166     //与indexOf功能一样,但是获得指定元素的最后出现的位置
 167     //对于重复的元素,只获取最后一个所在的位置
 168     public int lastIndexOf(Object o) {
 169         if (o == null) {
 170             for (int i = size-1; i >= 0; i--)
 171                 if (elementData[i]==null)
 172                     return i;
 173         } else {
 174             for (int i = size-1; i >= 0; i--)
 175                 if (o.equals(elementData[i]))
 176                     return i;
 177         }
 178         return -1;
 179     }
 180 
 181     //重写了Object中的clone方法,用于赋值容器,浅复制
 182     public Object clone() {
 183         try {
 184             ArrayList<?> v = (ArrayList<?>) super.clone();
 185             v.elementData = Arrays.copyOf(elementData, size);
 186             v.modCount = 0;
 187             return v;
 188         } catch (CloneNotSupportedException e) {
 189             // this shouldn't happen, since we are Cloneable
 190             throw new InternalError(e);
 191         }
 192     }
 193 
 194     //得到数组的副本
 195     public Object[] toArray() {
 196         return Arrays.copyOf(elementData, size);
 197     }
 198 
 199     //给定一个指定数组,返回指定数组大小,类型的副本
 200     @SuppressWarnings("unchecked")
 201     public <T> T[] toArray(T[] a) {
 202         if (a.length < size)
 203             // Make a new array of a's runtime type, but my contents:
 204             return (T[]) Arrays.copyOf(elementData, size, a.getClass());
 205         System.arraycopy(elementData, 0, a, 0, size);
 206         //如果a.length>size,则截取size的长度,有可能a本身就是有数据的,可能会出现a[size+?]有数据,所以a[size]设置为null来区别
 207         if (a.length > size)
 208             a[size] = null;
 209         return a;
 210     }
 211 
 212     // 不需要检查index的快速访问元素,只允许内部使用
 213     @SuppressWarnings("unchecked")
 214     E elementData(int index) {
 215         return (E) elementData[index];
 216     }
 217 
 218     //获取指定下标的元素
 219     public E get(int index) {
 220         rangeCheck(index);
 221         return elementData(index);
 222     }
 223 
 224     //用element新值去覆盖index位置的旧值
 225     public E set(int index, E element) {
 226         rangeCheck(index);
 227 
 228         E oldValue = elementData(index);
 229         elementData[index] = element;
 230         return oldValue;
 231     }
 232 
 233     //集合中新增一个元素,首先要确保在承受能力范围内,之后将新加入进来的元素赋值到数组的第size的位置上
 234     // 随后size+1, 新增的元素,插入到数组的末尾
 235     public boolean add(E e) {
 236         ensureCapacityInternal(size + 1);  // Increments modCount!!
 237         elementData[size++] = e;
 238         return true;
 239     }
 240 
 241     //插入一个元素element到指定index位置,原位置的元素依次向后移动一位
 242     //改方法效率要低一些,如果并不是特定必须要塞入哪个位置的话,最好不要用
 243     public void add(int index, E element) {
 244         //首先检查index是否可以使用
 245         rangeCheckForAdd(index);
 246         //确保数组可容纳
 247         ensureCapacityInternal(size + 1);  // Increments modCount!!
 248            //随后调用System.arraycopy方法,将elementData的index位置元素依次向后移动,为接下来的插入预留空间
 249         System.arraycopy(elementData, index, elementData, index + 1, size - index);
 250         //插入数据
 251         elementData[index] = element;
 252         size++;
 253     }
 254 
 255     //删除指定位置的元素
 256     public E remove(int index) {
 257         //下标检查
 258         rangeCheck(index);
 259         modCount++;
 260         //暂时保留旧值
 261         E oldValue = elementData(index);
 262         //从index+1位置开始的numMoved个元素,全部向前移动一位
 263         int numMoved = size - index - 1;
 264         if (numMoved > 0)
 265             System.arraycopy(elementData, index+1, elementData, index, numMoved);
 266         //最后一位设置为null                
 267         elementData[--size] = null;
 268         //返回被删除的值
 269         return oldValue;
 270     }
 271 
 272     //删除某个元素,对于重复的元素,只删除第一次出现的元素
 273     public boolean remove(Object o) {
 274         //删除null
 275         if (o == null) {
 276             for (int index = 0; index < size; index++)
 277                 if (elementData[index] == null) {
 278                     快速删除(不去做越界检查以及不返回结果,完全给本类自己使用的private方法)
 279                     fastRemove(index);
 280                     return true;
 281                 }
 282         } else {//删除非null的元素
 283             for (int index = 0; index < size; index++)
 284                 if (o.equals(elementData[index])) {
 285                     快速删除(不去做越界检查以及不返回结果,完全给本类自己使用的private方法)
 286                     fastRemove(index);
 287                     return true;
 288                 }
 289         }
 290         return false;
 291     }
 292 
 293     //快速删除:不去做越界检查以及不返回结果,完全给本类自己使用的private方法
 294     private void fastRemove(int index) {
 295         modCount++;
 296         int numMoved = size - index - 1;
 297         if (numMoved > 0)
 298             //从index+1位置开始的numMoved个元素,全部向前移动一位
 299             System.arraycopy(elementData, index+1, elementData, index, numMoved);
 300         elementData[--size] = null; // clear to let GC do its work
 301     }
 302 
 303     //清空数组
 304     public void clear() {
 305         modCount++;
 306         for (int i = 0; i < size; i++)
 307             elementData[i] = null;
 308         size = 0;
 309     }
 310 
 311     //添加一个集合C的全部元素,就是把集合中的数据全部复制过来
 312     public boolean addAll(Collection<? extends E> c) {
 313         Object[] a = c.toArray();
 314         int numNew = a.length;
 315         ensureCapacityInternal(size + numNew); 
 316         System.arraycopy(a, 0, elementData, size, numNew);
 317         size += numNew;
 318         return numNew != 0;
 319     }
 320 
 321     //指定index位置插入集合C中的全部元素,原来位置的元素依次向后移动
 322     public boolean addAll(int index, Collection<? extends E> c) {
 323         rangeCheckForAdd(index);
 324         Object[] a = c.toArray();
 325         int numNew = a.length;
 326         ensureCapacityInternal(size + numNew);  
 327         int numMoved = size - index;
 328         if (numMoved > 0)
 329             System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
 330         System.arraycopy(a, 0, elementData, index, numNew);
 331         size += numNew;
 332         return numNew != 0;
 333     }
 334 
 335     //  删除指定fromIndex~toIndex范围的元素,包含fromIndex,不包含toIndex
 336     protected void removeRange(int fromIndex, int toIndex) {
 337         modCount++;
 338         int numMoved = size - toIndex;
 339         System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved);
 340         int newSize = size - (toIndex-fromIndex);
 341         for (int i = newSize; i < size; i++) {
 342             elementData[i] = null;
 343         }
 344         size = newSize;
 345     }
 346 
 347     //index下标检查判断
 348     private void rangeCheck(int index) {
 349         if (index >= size)
 350             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 351     }
 352 
 353     //专门为add方法的index检查判断
 354     private void rangeCheckForAdd(int index) {
 355         if (index > size || index < 0)
 356             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 357     }
 358 
 359     //为IndexOutOfBoundsException提供信息的方法,告诉哪个位置出现了数组越界
 360     private String outOfBoundsMsg(int index) {
 361         return "Index: "+index+", Size: "+size;
 362     }
 363 
 364     //一次性删除多个元素
 365     public boolean removeAll(Collection<?> c) {
 366         Objects.requireNonNull(c);
 367         return batchRemove(c, false);
 368     }
 369 
 370     //保留当前容器与c的交集
 371     public boolean retainAll(Collection<?> c) {
 372         Objects.requireNonNull(c);
 373         return batchRemove(c, true);
 374     }
 375 
 376     //批量删除方法,complement为true表示求交集,如果为false表示在elementData中保留原有的非c的集合
 377     //也即true: a属于elementData同时a属于c; false: a属于elementData同时a不属于c
 378     private boolean batchRemove(Collection<?> c, boolean complement) {
 379         final Object[] elementData = this.elementData;
 380         int r = 0, w = 0;
 381         boolean modified = false;
 382         try {
 383             //一个读的index,一个是写的index,
 384             //因为每次都是把elementData数组拿来遍历,
 385             //注意complement是true还是false,
 386             //比方:complement为true: a属于elementData同时a属于c; false: a属于elementData同时a不属于c
 387             for (; r < size; r++)
 388                 if (c.contains(elementData[r]) == complement)
 389                     elementData[w++] = elementData[r];
 390         } finally {
 391             // 当c.contains()方法抛出异常的时候,就中断遍历,然后把从下标r开始的元素到结尾,全部移动到新数组的末尾接上。
 392             if (r != size) {
 393                 System.arraycopy(elementData, r,elementData, w, size - r);
 394                 w += size - r;
 395             }
 396             //清理数组中不需要的引用
 397             if (w != size) {
 398                 for (int i = w; i < size; i++)
 399                     elementData[i] = null;
 400                 modCount += size - w;
 401                 size = w;
 402                 modified = true;
 403             }
 404         }
 405         return modified;
 406     }
 407 
 408     //序列化:保存数组实例的状态到一个流
 409     private void writeObject(java.io.ObjectOutputStream s)
 410         throws java.io.IOException{
 411         // Write out element count, and any hidden stuff
 412         int expectedModCount = modCount;
 413         s.defaultWriteObject();
 414         // Write out size as capacity for behavioural compatibility with clone()
 415         s.writeInt(size);
 416         // Write out all elements in the proper order.
 417         for (int i=0; i<size; i++) {
 418             s.writeObject(elementData[i]);
 419         }
 420         if (modCount != expectedModCount) {
 421             throw new ConcurrentModificationException();
 422         }
 423     }
 424 
 425     //反序列化:从一个流中读出数组实例的状态
 426     private void readObject(java.io.ObjectInputStream s)
 427         throws java.io.IOException, ClassNotFoundException {
 428         elementData = EMPTY_ELEMENTDATA;
 429         s.defaultReadObject();
 430         s.readInt();
 431         if (size > 0) {
 432             // be like clone(), allocate array based upon size not capacity
 433             int capacity = calculateCapacity(elementData, size);
 434             SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
 435             ensureCapacityInternal(size);
 436             Object[] a = elementData;
 437             // Read in all elements in the proper order.
 438             for (int i=0; i<size; i++) {
 439                 a[i] = s.readObject();
 440             }
 441         }
 442     }
 443 
 444 
 445     //返回一个list迭代器,链表迭代器,可以双向迭代,还具有add方法,
 446     //但是只有在list类型中才可以使用,别的集合类没有
 447     //接受一个Index,确定迭代器初始的位置
 448     public ListIterator<E> listIterator(int index) {
 449         if (index < 0 || index > size)
 450             throw new IndexOutOfBoundsException("Index: "+index);
 451         return new ListItr(index);
 452     }
 453 
 454  
 455     public ListIterator<E> listIterator() {
 456         return new ListItr(0);
 457     }
 458 
 459     public Iterator<E> iterator() {
 460         return new Itr();
 461     }
 462 
 463      //AbstractList.Itr的优化版本迭代器
 464     private class Itr implements Iterator<E> {
 465         int cursor;       // 下一个要被返回的元素下标
 466         int lastRet = -1; // 上一个要被返回的元素下标,如果没有,就默认为-1
 467         int expectedModCount = modCount;
 468 
 469         Itr() {}
 470         
 471         //判断是否还有下一个元素
 472         public boolean hasNext() {
 473             return cursor != size;
 474         }
 475 
 476         //返回下一个元素,默认一开始的next是第一个元素
 477         @SuppressWarnings("unchecked")
 478         public E next() {
 479             //快速失败检测
 480             checkForComodification();
 481             int i = cursor;
 482             //会判断一次位置是否合法,因为cursor只是盲目的+1
 483             if (i >= size)
 484                 throw new NoSuchElementException();
 485             Object[] elementData = ArrayList.this.elementData;
 486             if (i >= elementData.length)
 487                 throw new ConcurrentModificationException();
 488             cursor = i + 1;//cursor设置为下一个要被返回的元素下标
 489             return (E) elementData[lastRet = i];//将lastRet设置为被返回的元素下标
 490         }
 491 
 492         //删除上一个元素
 493         public void remove() {
 494             if (lastRet < 0)
 495                 throw new IllegalStateException();
 496             checkForComodification();
 497 
 498             try {
 499                 ArrayList.this.remove(lastRet);//删除的是下标为lastRet元素
 500                 cursor = lastRet;//回退
 501                 //设置成为-1,也即不能连续的删除,该类不能够往回走,
 502                 //只能继续前进,因为继续删除,会抛出IllegalStateException异常
 503                 lastRet = -1;
 504                 expectedModCount = modCount;
 505             } catch (IndexOutOfBoundsException ex) {
 506                 throw new ConcurrentModificationException();
 507             }
 508         }
 509 
 510         //遍历余下的元素
 511         @Override
 512         @SuppressWarnings("unchecked")
 513         public void forEachRemaining(Consumer<? super E> consumer) {
 514             Objects.requireNonNull(consumer);
 515             final int size = ArrayList.this.size;
 516             int i = cursor;
 517             if (i >= size) {
 518                 return;
 519             }
 520             final Object[] elementData = ArrayList.this.elementData;
 521             if (i >= elementData.length) {
 522                 throw new ConcurrentModificationException();
 523             }
 524             ////此处接受elementData元素,执行consumer中的方法,可能会去改变elementData元素
 525             while (i != size && modCount == expectedModCount) {
 526                 consumer.accept((E) elementData[i++]);
 527             }
 528             // update once at end of iteration to reduce heap write traffic
 529             cursor = i;
 530             lastRet = i - 1;
 531             checkForComodification();
 532         }
 533 
 534         final void checkForComodification() {
 535             if (modCount != expectedModCount)
 536                 throw new ConcurrentModificationException();
 537         }
 538     }
 539 
 540        //一个对AbstractList.ListItr的优化版本链表迭代器
 541     private class ListItr extends Itr implements ListIterator<E> {
 542         ListItr(int index) {
 543             super();
 544             cursor = index;
 545         }
 546         public boolean hasPrevious() {
 547             return cursor != 0;
 548         }
 549         public int nextIndex() {
 550             return cursor;
 551         }
 552         public int previousIndex() {
 553             return cursor - 1;
 554         }
 555         //返回上一个元素
 556         @SuppressWarnings("unchecked")
 557         public E previous() {
 558             checkForComodification();
 559             int i = cursor - 1;
 560             if (i < 0)
 561                 throw new NoSuchElementException();
 562             Object[] elementData = ArrayList.this.elementData;
 563             if (i >= elementData.length)
 564                 throw new ConcurrentModificationException();
 565             cursor = i;
 566             return (E) elementData[lastRet = i];
 567         }
 568 
 569         //更新上一个位置的元素,将其置换成e
 570         public void set(E e) {
 571             if (lastRet < 0)
 572                 throw new IllegalStateException();
 573             checkForComodification();
 574 
 575             try {
 576                 ArrayList.this.set(lastRet, e);
 577             } catch (IndexOutOfBoundsException ex) {
 578                 throw new ConcurrentModificationException();
 579             }
 580         }
 581 
 582         //新增一个元素,处在上一个元素之后,下一个元素之前,会移动数组
 583         public void add(E e) {
 584             checkForComodification();
 585 
 586             try {
 587                 int i = cursor;
 588                 ArrayList.this.add(i, e);
 589                 cursor = i + 1;
 590                 lastRet = -1;
 591                 expectedModCount = modCount;
 592             } catch (IndexOutOfBoundsException ex) {
 593                 throw new ConcurrentModificationException();
 594             }
 595         }
 596     }
 597 
 598     //得到从fromIndex~toIndex位置的子列表
 599     public List<E> subList(int fromIndex, int toIndex) {
 600         subListRangeCheck(fromIndex, toIndex, size);
 601         return new SubList(this, 0, fromIndex, toIndex);
 602     }
 603 
 604     //判断Index是否合法
 605     static void subListRangeCheck(int fromIndex, int toIndex, int size) {
 606         if (fromIndex < 0)
 607             throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
 608         if (toIndex > size)
 609             throw new IndexOutOfBoundsException("toIndex = " + toIndex);
 610         if (fromIndex > toIndex)
 611             throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
 612     }
 613 
 614     //继承与AbstractList的SubList类,其实这个类,只是去封装了几个属性,实际上用的还是原来ArrayList类的数组,外观模式
 615     private class SubList extends AbstractList<E> implements RandomAccess {
 616         private final AbstractList<E> parent;
 617         private final int parentOffset;
 618         private final int offset;
 619         int size;
 620 
 621         //参数:
 622         //parent 父类型
 623         //offset 父类型的偏移量
 624         //fromIndex 子列表的开始元素,位于父列表的位置
 625         //toIndex 子列表的结束元素,位于父列表的位置
 626         SubList(AbstractList<E> parent,
 627                 int offset, int fromIndex, int toIndex) {
 628             this.parent = parent;
 629             this.parentOffset = fromIndex;
 630             this.offset = offset + fromIndex;
 631             this.size = toIndex - fromIndex;
 632             this.modCount = ArrayList.this.modCount;
 633         }
 634 
 635         public E set(int index, E e) {
 636             rangeCheck(index);
 637             checkForComodification();
 638             E oldValue = ArrayList.this.elementData(offset + index);
 639             ArrayList.this.elementData[offset + index] = e;
 640             return oldValue;
 641         }
 642 
 643         public E get(int index) {
 644             rangeCheck(index);
 645             checkForComodification();
 646             return ArrayList.this.elementData(offset + index);
 647         }
 648 
 649         public int size() {
 650             checkForComodification();
 651             return this.size;
 652         }
 653 
 654         public void add(int index, E e) {
 655             rangeCheckForAdd(index);
 656             checkForComodification();
 657             parent.add(parentOffset + index, e);
 658             this.modCount = parent.modCount;
 659             this.size++;
 660         }
 661 
 662         public E remove(int index) {
 663             rangeCheck(index);
 664             checkForComodification();
 665             E result = parent.remove(parentOffset + index);
 666             this.modCount = parent.modCount;
 667             this.size--;
 668             return result;
 669         }
 670 
 671         protected void removeRange(int fromIndex, int toIndex) {
 672             checkForComodification();
 673             parent.removeRange(parentOffset + fromIndex,
 674                                parentOffset + toIndex);
 675             this.modCount = parent.modCount;
 676             this.size -= toIndex - fromIndex;
 677         }
 678 
 679         public boolean addAll(Collection<? extends E> c) {
 680             return addAll(this.size, c);
 681         }
 682 
 683         public boolean addAll(int index, Collection<? extends E> c) {
 684             rangeCheckForAdd(index);
 685             int cSize = c.size();
 686             if (cSize==0)
 687                 return false;
 688 
 689             checkForComodification();
 690             parent.addAll(parentOffset + index, c);
 691             this.modCount = parent.modCount;
 692             this.size += cSize;
 693             return true;
 694         }
 695 
 696         public Iterator<E> iterator() {
 697             return listIterator();
 698         }
 699 
 700         public ListIterator<E> listIterator(final int index) {
 701             checkForComodification();
 702             rangeCheckForAdd(index);
 703             final int offset = this.offset;
 704 
 705             return new ListIterator<E>() {
 706                 int cursor = index;
 707                 int lastRet = -1;
 708                 int expectedModCount = ArrayList.this.modCount;
 709 
 710                 public boolean hasNext() {
 711                     return cursor != SubList.this.size;
 712                 }
 713 
 714                 @SuppressWarnings("unchecked")
 715                 public E next() {
 716                     checkForComodification();
 717                     int i = cursor;
 718                     if (i >= SubList.this.size)
 719                         throw new NoSuchElementException();
 720                     Object[] elementData = ArrayList.this.elementData;
 721                     if (offset + i >= elementData.length)
 722                         throw new ConcurrentModificationException();
 723                     cursor = i + 1;
 724                     return (E) elementData[offset + (lastRet = i)];
 725                 }
 726 
 727                 public boolean hasPrevious() {
 728                     return cursor != 0;
 729                 }
 730 
 731                 @SuppressWarnings("unchecked")
 732                 public E previous() {
 733                     checkForComodification();
 734                     int i = cursor - 1;
 735                     if (i < 0)
 736                         throw new NoSuchElementException();
 737                     Object[] elementData = ArrayList.this.elementData;
 738                     if (offset + i >= elementData.length)
 739                         throw new ConcurrentModificationException();
 740                     cursor = i;
 741                     return (E) elementData[offset + (lastRet = i)];
 742                 }
 743 
 744                 @SuppressWarnings("unchecked")
 745                 public void forEachRemaining(Consumer<? super E> consumer) {
 746                     Objects.requireNonNull(consumer);
 747                     final int size = SubList.this.size;
 748                     int i = cursor;
 749                     if (i >= size) {
 750                         return;
 751                     }
 752                     final Object[] elementData = ArrayList.this.elementData;
 753                     if (offset + i >= elementData.length) {
 754                         throw new ConcurrentModificationException();
 755                     }
 756                     while (i != size && modCount == expectedModCount) {
 757                         consumer.accept((E) elementData[offset + (i++)]);
 758                     }
 759                     // update once at end of iteration to reduce heap write traffic
 760                     lastRet = cursor = i;
 761                     checkForComodification();
 762                 }
 763 
 764                 public int nextIndex() {
 765                     return cursor;
 766                 }
 767 
 768                 public int previousIndex() {
 769                     return cursor - 1;
 770                 }
 771 
 772                 public void remove() {
 773                     if (lastRet < 0)
 774                         throw new IllegalStateException();
 775                     checkForComodification();
 776 
 777                     try {
 778                         SubList.this.remove(lastRet);
 779                         cursor = lastRet;
 780                         lastRet = -1;
 781                         expectedModCount = ArrayList.this.modCount;
 782                     } catch (IndexOutOfBoundsException ex) {
 783                         throw new ConcurrentModificationException();
 784                     }
 785                 }
 786 
 787                 public void set(E e) {
 788                     if (lastRet < 0)
 789                         throw new IllegalStateException();
 790                     checkForComodification();
 791 
 792                     try {
 793                         ArrayList.this.set(offset + lastRet, e);
 794                     } catch (IndexOutOfBoundsException ex) {
 795                         throw new ConcurrentModificationException();
 796                     }
 797                 }
 798 
 799                 public void add(E e) {
 800                     checkForComodification();
 801 
 802                     try {
 803                         int i = cursor;
 804                         SubList.this.add(i, e);
 805                         cursor = i + 1;
 806                         lastRet = -1;
 807                         expectedModCount = ArrayList.this.modCount;
 808                     } catch (IndexOutOfBoundsException ex) {
 809                         throw new ConcurrentModificationException();
 810                     }
 811                 }
 812 
 813                 final void checkForComodification() {
 814                     if (expectedModCount != ArrayList.this.modCount)
 815                         throw new ConcurrentModificationException();
 816                 }
 817             };
 818         }
 819 
 820         public List<E> subList(int fromIndex, int toIndex) {
 821             subListRangeCheck(fromIndex, toIndex, size);
 822             return new SubList(this, offset, fromIndex, toIndex);
 823         }
 824 
 825         private void rangeCheck(int index) {
 826             if (index < 0 || index >= this.size)
 827                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 828         }
 829 
 830         private void rangeCheckForAdd(int index) {
 831             if (index < 0 || index > this.size)
 832                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 833         }
 834 
 835         private String outOfBoundsMsg(int index) {
 836             return "Index: "+index+", Size: "+this.size;
 837         }
 838 
 839         private void checkForComodification() {
 840             if (ArrayList.this.modCount != this.modCount)
 841                 throw new ConcurrentModificationException();
 842         }
 843 
 844         public Spliterator<E> spliterator() {
 845             checkForComodification();
 846             return new ArrayListSpliterator<E>(ArrayList.this, offset,
 847                                                offset + this.size, this.modCount);
 848         }
 849     }
 850 
 851     //与forEachRemaining很像,一个是迭代所有,一个是迭代剩余,都会去执行Consumer中定义的方法,可能会改变元素的值
 852     @Override
 853     public void forEach(Consumer<? super E> action) {
 854         Objects.requireNonNull(action);
 855         final int expectedModCount = modCount;
 856         @SuppressWarnings("unchecked")
 857         final E[] elementData = (E[]) this.elementData;
 858         final int size = this.size;
 859         for (int i=0; modCount == expectedModCount && i < size; i++) {
 860             action.accept(elementData[i]);
 861         }
 862         if (modCount != expectedModCount) {
 863             throw new ConcurrentModificationException();
 864         }
 865     }
 866 
 867     //返回spliterator,用于并行计算中,splitable iterator可分割迭代器
 868     @Override
 869     public Spliterator<E> spliterator() {
 870         return new ArrayListSpliterator<>(this, 0, -1, 0);
 871     }
 872 
 873     
 874     static final class ArrayListSpliterator<E> implements Spliterator<E> {
 875 
 876         private final ArrayList<E> list;//原数组
 877         private int index; // current index, modified on advance/split
 878         private int fence; // -1 until used; then one past last index
 879         private int expectedModCount; // initialized when fence set
 880 
 881         
 882         ArrayListSpliterator(ArrayList<E> list, int origin, int fence,int expectedModCount) {
 883             this.list = list; // OK if null unless traversed
 884             this.index = origin;
 885             this.fence = fence;
 886             this.expectedModCount = expectedModCount;
 887         }
 888 
 889         // 第一次使用时,初始化fence大小
 890         private int getFence() { // initialize fence to size on first use
 891             int hi; // (a specialized variant appears in method forEach)
 892             ArrayList<E> lst;
 893             if ((hi = fence) < 0) {//-1表示初始化的值
 894                 if ((lst = list) == null)
 895                     hi = fence = 0;
 896                 else {
 897                     expectedModCount = lst.modCount;
 898                     hi = fence = lst.size;
 899                 }
 900             }
 901             return hi;
 902         }
 903 
 904         public ArrayListSpliterator<E> trySplit() {
 905             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
 906             return (lo >= mid) ? null : // divide range in half unless too small
 907                 new ArrayListSpliterator<E>(list, lo, index = mid,
 908                                             expectedModCount);
 909         }
 910 
 911         public boolean tryAdvance(Consumer<? super E> action) {
 912             if (action == null)
 913                 throw new NullPointerException();
 914             int hi = getFence(), i = index;
 915             if (i < hi) {
 916                 index = i + 1;
 917                 @SuppressWarnings("unchecked") E e = (E)list.elementData[i];
 918                 action.accept(e);
 919                 if (list.modCount != expectedModCount)
 920                     throw new ConcurrentModificationException();
 921                 return true;
 922             }
 923             return false;
 924         }
 925 
 926         public void forEachRemaining(Consumer<? super E> action) {
 927             int i, hi, mc; // hoist accesses and checks from loop
 928             ArrayList<E> lst; Object[] a;
 929             if (action == null)
 930                 throw new NullPointerException();
 931             if ((lst = list) != null && (a = lst.elementData) != null) {
 932                 if ((hi = fence) < 0) {
 933                     mc = lst.modCount;
 934                     hi = lst.size;
 935                 }
 936                 else
 937                     mc = expectedModCount;
 938                 if ((i = index) >= 0 && (index = hi) <= a.length) {
 939                     for (; i < hi; ++i) {
 940                         @SuppressWarnings("unchecked") E e = (E) a[i];
 941                         action.accept(e);
 942                     }
 943                     if (lst.modCount == mc)
 944                         return;
 945                 }
 946             }
 947             throw new ConcurrentModificationException();
 948         }
 949 
 950         public long estimateSize() {
 951             return (long) (getFence() - index);
 952         }
 953 
 954         public int characteristics() {
 955             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
 956         }
 957     }
 958 
 959     @Override
 960     public boolean removeIf(Predicate<? super E> filter) {
 961         Objects.requireNonNull(filter);
 962         int removeCount = 0;
 963         final BitSet removeSet = new BitSet(size);
 964         final int expectedModCount = modCount;
 965         final int size = this.size;
 966         for (int i=0; modCount == expectedModCount && i < size; i++) {
 967             @SuppressWarnings("unchecked")
 968             final E element = (E) elementData[i];
 969             if (filter.test(element)) {
 970                 removeSet.set(i);
 971                 removeCount++;
 972             }
 973         }
 974         if (modCount != expectedModCount) {
 975             throw new ConcurrentModificationException();
 976         }
 977 
 978         // shift surviving elements left over the spaces left by removed elements
 979         final boolean anyToRemove = removeCount > 0;
 980         if (anyToRemove) {
 981             final int newSize = size - removeCount;
 982             for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
 983                 i = removeSet.nextClearBit(i);
 984                 elementData[j] = elementData[i];
 985             }
 986             for (int k=newSize; k < size; k++) {
 987                 elementData[k] = null;  // Let gc do its work
 988             }
 989             this.size = newSize;
 990             if (modCount != expectedModCount) {
 991                 throw new ConcurrentModificationException();
 992             }
 993             modCount++;
 994         }
 995 
 996         return anyToRemove;
 997     }
 998 
 999     //替换所有
1000     @Override
1001     @SuppressWarnings("unchecked")
1002     public void replaceAll(UnaryOperator<E> operator) {
1003         Objects.requireNonNull(operator);
1004         final int expectedModCount = modCount;
1005         final int size = this.size;
1006         for (int i=0; modCount == expectedModCount && i < size; i++) {
1007             elementData[i] = operator.apply((E) elementData[i]);
1008         }
1009         if (modCount != expectedModCount) {
1010             throw new ConcurrentModificationException();
1011         }
1012         modCount++;
1013     }
1014 
1015     //排序
1016     @Override
1017     @SuppressWarnings("unchecked")
1018     public void sort(Comparator<? super E> c) {
1019         final int expectedModCount = modCount;
1020         Arrays.sort((E[]) elementData, 0, size, c);
1021         if (modCount != expectedModCount) {
1022             throw new ConcurrentModificationException();
1023         }
1024         modCount++;
1025     }
1026 }