1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 
  28 import java.util.function.Consumer;
  29 import java.util.function.Predicate;
  30 import java.util.function.UnaryOperator;
  31 import jdk.internal.access.SharedSecrets;
  32 
  33 /**
  34  * Resizable-array implementation of the {@code List} interface.  Implements
  35  * all optional list operations, and permits all elements, including
  36  * {@code null}.  In addition to implementing the {@code List} interface,
  37  * this class provides methods to manipulate the size of the array that is
  38  * used internally to store the list.  (This class is roughly equivalent to
  39  * {@code Vector}, except that it is unsynchronized.)
  40  *
  41  * <p>The {@code size}, {@code isEmpty}, {@code get}, {@code set},
  42  * {@code iterator}, and {@code listIterator} operations run in constant
  43  * time.  The {@code add} operation runs in <i>amortized constant time</i>,
  44  * that is, adding n elements requires O(n) time.  All of the other operations
  45  * run in linear time (roughly speaking).  The constant factor is low compared
  46  * to that for the {@code LinkedList} implementation.
  47  *
  48  * <p>Each {@code ArrayList} instance has a <i>capacity</i>.  The capacity is
  49  * the size of the array used to store the elements in the list.  It is always
  50  * at least as large as the list size.  As elements are added to an ArrayList,
  51  * its capacity grows automatically.  The details of the growth policy are not
  52  * specified beyond the fact that adding an element has constant amortized
  53  * time cost.
  54  *
  55  * <p>An application can increase the capacity of an {@code ArrayList} instance
  56  * before adding a large number of elements using the {@code ensureCapacity}
  57  * operation.  This may reduce the amount of incremental reallocation.
  58  *
  59  * <p><strong>Note that this implementation is not synchronized.</strong>
  60  * If multiple threads access an {@code ArrayList} instance concurrently,
  61  * and at least one of the threads modifies the list structurally, it
  62  * <i>must</i> be synchronized externally.  (A structural modification is
  63  * any operation that adds or deletes one or more elements, or explicitly
  64  * resizes the backing array; merely setting the value of an element is not
  65  * a structural modification.)  This is typically accomplished by
  66  * synchronizing on some object that naturally encapsulates the list.
  67  *
  68  * If no such object exists, the list should be "wrapped" using the
  69  * {@link Collections#synchronizedList Collections.synchronizedList}
  70  * method.  This is best done at creation time, to prevent accidental
  71  * unsynchronized access to the list:<pre>
  72  *   List list = Collections.synchronizedList(new ArrayList(...));</pre>
  73  *
  74  * <p id="fail-fast">
  75  * The iterators returned by this class's {@link #iterator() iterator} and
  76  * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
  77  * if the list is structurally modified at any time after the iterator is
  78  * created, in any way except through the iterator's own
  79  * {@link ListIterator#remove() remove} or
  80  * {@link ListIterator#add(Object) add} methods, the iterator will throw a
  81  * {@link ConcurrentModificationException}.  Thus, in the face of
  82  * concurrent modification, the iterator fails quickly and cleanly, rather
  83  * than risking arbitrary, non-deterministic behavior at an undetermined
  84  * time in the future.
  85  *
  86  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  87  * as it is, generally speaking, impossible to make any hard guarantees in the
  88  * presence of unsynchronized concurrent modification.  Fail-fast iterators
  89  * throw {@code ConcurrentModificationException} on a best-effort basis.
  90  * Therefore, it would be wrong to write a program that depended on this
  91  * exception for its correctness:  <i>the fail-fast behavior of iterators
  92  * should be used only to detect bugs.</i>
  93  *
  94  * <p>This class is a member of the
  95  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
  96  * Java Collections Framework</a>.
  97  *
  98  * @param <E> the type of elements in this list
  99  *
 100  * @author  Josh Bloch
 101  * @author  Neal Gafter
 102  * @see     Collection
 103  * @see     List
 104  * @see     LinkedList
 105  * @see     Vector
 106  * @since   1.2
 107  */
 108 public class ArrayList<E> extends AbstractList<E>
 109         implements List<E>, RandomAccess, Cloneable, java.io.Serializable
 110 {
 111     private static final long serialVersionUID = 8683452581122892189L;
 112 
 113     /**
 114      * Default initial capacity.
 115      */
 116     private static final int DEFAULT_CAPACITY = 10;
 117 
 118     /**
 119      * Shared empty array instance used for empty instances.
 120      */
 121     private static final Object[] EMPTY_ELEMENTDATA = {};
 122 
 123     /**
 124      * Shared empty array instance used for default sized empty instances. We
 125      * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
 126      * first element is added.
 127      */
 128     private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
 129 
 130     /**
 131      * The array buffer into which the elements of the ArrayList are stored.
 132      * The capacity of the ArrayList is the length of this array buffer. Any
 133      * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 134      * will be expanded to DEFAULT_CAPACITY when the first element is added.
 135      */
 136     transient Object[] elementData; // non-private to simplify nested class access
 137 
 138     /**
 139      * The size of the ArrayList (the number of elements it contains).
 140      *
 141      * @serial
 142      */
 143     private int size;
 144 
 145     /**
 146      * Constructs an empty list with the specified initial capacity.
 147      *
 148      * @param  initialCapacity  the initial capacity of the list
 149      * @throws IllegalArgumentException if the specified initial capacity
 150      *         is negative
 151      */
 152     public ArrayList(int initialCapacity) {
 153         if (initialCapacity > 0) {
 154             this.elementData = new Object[initialCapacity];
 155         } else if (initialCapacity == 0) {
 156             this.elementData = EMPTY_ELEMENTDATA;
 157         } else {
 158             throw new IllegalArgumentException("Illegal Capacity: "+
 159                                                initialCapacity);
 160         }
 161     }
 162 
 163     /**
 164      * Constructs an empty list with an initial capacity of ten.
 165      */
 166     public ArrayList() {
 167         this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
 168     }
 169 
 170     /**
 171      * Constructs a list containing the elements of the specified
 172      * collection, in the order they are returned by the collection's
 173      * iterator.
 174      *
 175      * @param c the collection whose elements are to be placed into this list
 176      * @throws NullPointerException if the specified collection is null
 177      */
 178     public ArrayList(Collection<? extends E> c) {
 179         if (c instanceof ArrayList) {
 180             elementData = new Object[((ArrayList)c).elementData.length];
 181             System.arraycopy(((ArrayList)c).elementData, 0, elementData, 0, ((ArrayList)c).elementData.length);
 182             size = ((ArrayList)c).size;
 183         } else {
 184             elementData = c.toArray();
 185             if ((size = elementData.length) != 0) {
 186                 // defend against c.toArray (incorrectly) not returning Object[]
 187                 // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
 188                 if (elementData.getClass() != Object[].class)
 189                     elementData = Arrays.copyOf(elementData, size, Object[].class);
 190             } else {
 191                 // replace with empty array.
 192                 this.elementData = EMPTY_ELEMENTDATA;
 193             }
 194         }
 195     }
 196 
 197     /**
 198      * Trims the capacity of this {@code ArrayList} instance to be the
 199      * list's current size.  An application can use this operation to minimize
 200      * the storage of an {@code ArrayList} instance.
 201      */
 202     public void trimToSize() {
 203         modCount++;
 204         if (size < elementData.length) {
 205             elementData = (size == 0)
 206               ? EMPTY_ELEMENTDATA
 207               : Arrays.copyOf(elementData, size);
 208         }
 209     }
 210 
 211     /**
 212      * Increases the capacity of this {@code ArrayList} instance, if
 213      * necessary, to ensure that it can hold at least the number of elements
 214      * specified by the minimum capacity argument.
 215      *
 216      * @param minCapacity the desired minimum capacity
 217      */
 218     public void ensureCapacity(int minCapacity) {
 219         if (minCapacity > elementData.length
 220             && !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 221                  && minCapacity <= DEFAULT_CAPACITY)) {
 222             modCount++;
 223             grow(minCapacity);
 224         }
 225     }
 226 
 227     /**
 228      * The maximum size of array to allocate (unless necessary).
 229      * Some VMs reserve some header words in an array.
 230      * Attempts to allocate larger arrays may result in
 231      * OutOfMemoryError: Requested array size exceeds VM limit
 232      */
 233     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 234 
 235     /**
 236      * Increases the capacity to ensure that it can hold at least the
 237      * number of elements specified by the minimum capacity argument.
 238      *
 239      * @param minCapacity the desired minimum capacity
 240      * @throws OutOfMemoryError if minCapacity is less than zero
 241      */
 242     private Object[] grow(int minCapacity) {
 243         return elementData = Arrays.copyOf(elementData,
 244                                            newCapacity(minCapacity));
 245     }
 246 
 247     private Object[] grow() {
 248         return grow(size + 1);
 249     }
 250 
 251     /**
 252      * Returns a capacity at least as large as the given minimum capacity.
 253      * Returns the current capacity increased by 50% if that suffices.
 254      * Will not return a capacity greater than MAX_ARRAY_SIZE unless
 255      * the given minimum capacity is greater than MAX_ARRAY_SIZE.
 256      *
 257      * @param minCapacity the desired minimum capacity
 258      * @throws OutOfMemoryError if minCapacity is less than zero
 259      */
 260     private int newCapacity(int minCapacity) {
 261         // overflow-conscious code
 262         int oldCapacity = elementData.length;
 263         int newCapacity = oldCapacity + (oldCapacity >> 1);
 264         if (newCapacity - minCapacity <= 0) {
 265             if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
 266                 return Math.max(DEFAULT_CAPACITY, minCapacity);
 267             if (minCapacity < 0) // overflow
 268                 throw new OutOfMemoryError();
 269             return minCapacity;
 270         }
 271         return (newCapacity - MAX_ARRAY_SIZE <= 0)
 272             ? newCapacity
 273             : hugeCapacity(minCapacity);
 274     }
 275 
 276     private static int hugeCapacity(int minCapacity) {
 277         if (minCapacity < 0) // overflow
 278             throw new OutOfMemoryError();
 279         return (minCapacity > MAX_ARRAY_SIZE)
 280             ? Integer.MAX_VALUE
 281             : MAX_ARRAY_SIZE;
 282     }
 283 
 284     /**
 285      * Returns the number of elements in this list.
 286      *
 287      * @return the number of elements in this list
 288      */
 289     public int size() {
 290         return size;
 291     }
 292 
 293     /**
 294      * Returns {@code true} if this list contains no elements.
 295      *
 296      * @return {@code true} if this list contains no elements
 297      */
 298     public boolean isEmpty() {
 299         return size == 0;
 300     }
 301 
 302     /**
 303      * Returns {@code true} if this list contains the specified element.
 304      * More formally, returns {@code true} if and only if this list contains
 305      * at least one element {@code e} such that
 306      * {@code Objects.equals(o, e)}.
 307      *
 308      * @param o element whose presence in this list is to be tested
 309      * @return {@code true} if this list contains the specified element
 310      */
 311     public boolean contains(Object o) {
 312         return indexOf(o) >= 0;
 313     }
 314 
 315     /**
 316      * Returns the index of the first occurrence of the specified element
 317      * in this list, or -1 if this list does not contain the element.
 318      * More formally, returns the lowest index {@code i} such that
 319      * {@code Objects.equals(o, get(i))},
 320      * or -1 if there is no such index.
 321      */
 322     public int indexOf(Object o) {
 323         return indexOfRange(o, 0, size);
 324     }
 325 
 326     int indexOfRange(Object o, int start, int end) {
 327         Object[] es = elementData;
 328         if (o == null) {
 329             for (int i = start; i < end; i++) {
 330                 if (es[i] == null) {
 331                     return i;
 332                 }
 333             }
 334         } else {
 335             for (int i = start; i < end; i++) {
 336                 if (o.equals(es[i])) {
 337                     return i;
 338                 }
 339             }
 340         }
 341         return -1;
 342     }
 343 
 344     /**
 345      * Returns the index of the last occurrence of the specified element
 346      * in this list, or -1 if this list does not contain the element.
 347      * More formally, returns the highest index {@code i} such that
 348      * {@code Objects.equals(o, get(i))},
 349      * or -1 if there is no such index.
 350      */
 351     public int lastIndexOf(Object o) {
 352         return lastIndexOfRange(o, 0, size);
 353     }
 354 
 355     int lastIndexOfRange(Object o, int start, int end) {
 356         Object[] es = elementData;
 357         if (o == null) {
 358             for (int i = end - 1; i >= start; i--) {
 359                 if (es[i] == null) {
 360                     return i;
 361                 }
 362             }
 363         } else {
 364             for (int i = end - 1; i >= start; i--) {
 365                 if (o.equals(es[i])) {
 366                     return i;
 367                 }
 368             }
 369         }
 370         return -1;
 371     }
 372 
 373     /**
 374      * Returns a shallow copy of this {@code ArrayList} instance.  (The
 375      * elements themselves are not copied.)
 376      *
 377      * @return a clone of this {@code ArrayList} instance
 378      */
 379     public Object clone() {
 380         try {
 381             ArrayList<?> v = (ArrayList<?>) super.clone();
 382             v.elementData = Arrays.copyOf(elementData, size);
 383             v.modCount = 0;
 384             return v;
 385         } catch (CloneNotSupportedException e) {
 386             // this shouldn't happen, since we are Cloneable
 387             throw new InternalError(e);
 388         }
 389     }
 390 
 391     /**
 392      * Returns an array containing all of the elements in this list
 393      * in proper sequence (from first to last element).
 394      *
 395      * <p>The returned array will be "safe" in that no references to it are
 396      * maintained by this list.  (In other words, this method must allocate
 397      * a new array).  The caller is thus free to modify the returned array.
 398      *
 399      * <p>This method acts as bridge between array-based and collection-based
 400      * APIs.
 401      *
 402      * @return an array containing all of the elements in this list in
 403      *         proper sequence
 404      */
 405     public Object[] toArray() {
 406         return Arrays.copyOf(elementData, size);
 407     }
 408 
 409     /**
 410      * Returns an array containing all of the elements in this list in proper
 411      * sequence (from first to last element); the runtime type of the returned
 412      * array is that of the specified array.  If the list fits in the
 413      * specified array, it is returned therein.  Otherwise, a new array is
 414      * allocated with the runtime type of the specified array and the size of
 415      * this list.
 416      *
 417      * <p>If the list fits in the specified array with room to spare
 418      * (i.e., the array has more elements than the list), the element in
 419      * the array immediately following the end of the collection is set to
 420      * {@code null}.  (This is useful in determining the length of the
 421      * list <i>only</i> if the caller knows that the list does not contain
 422      * any null elements.)
 423      *
 424      * @param a the array into which the elements of the list are to
 425      *          be stored, if it is big enough; otherwise, a new array of the
 426      *          same runtime type is allocated for this purpose.
 427      * @return an array containing the elements of the list
 428      * @throws ArrayStoreException if the runtime type of the specified array
 429      *         is not a supertype of the runtime type of every element in
 430      *         this list
 431      * @throws NullPointerException if the specified array is null
 432      */
 433     @SuppressWarnings("unchecked")
 434     public <T> T[] toArray(T[] a) {
 435         if (a.length < size)
 436             // Make a new array of a's runtime type, but my contents:
 437             return (T[]) Arrays.copyOf(elementData, size, a.getClass());
 438         System.arraycopy(elementData, 0, a, 0, size);
 439         if (a.length > size)
 440             a[size] = null;
 441         return a;
 442     }
 443 
 444     // Positional Access Operations
 445 
 446     @SuppressWarnings("unchecked")
 447     E elementData(int index) {
 448         return (E) elementData[index];
 449     }
 450 
 451     @SuppressWarnings("unchecked")
 452     static <E> E elementAt(Object[] es, int index) {
 453         return (E) es[index];
 454     }
 455 
 456     /**
 457      * Returns the element at the specified position in this list.
 458      *
 459      * @param  index index of the element to return
 460      * @return the element at the specified position in this list
 461      * @throws IndexOutOfBoundsException {@inheritDoc}
 462      */
 463     public E get(int index) {
 464         Objects.checkIndex(index, size);
 465         return elementData(index);
 466     }
 467 
 468     /**
 469      * Replaces the element at the specified position in this list with
 470      * the specified element.
 471      *
 472      * @param index index of the element to replace
 473      * @param element element to be stored at the specified position
 474      * @return the element previously at the specified position
 475      * @throws IndexOutOfBoundsException {@inheritDoc}
 476      */
 477     public E set(int index, E element) {
 478         Objects.checkIndex(index, size);
 479         E oldValue = elementData(index);
 480         elementData[index] = element;
 481         return oldValue;
 482     }
 483 
 484     /**
 485      * This helper method split out from add(E) to keep method
 486      * bytecode size under 35 (the -XX:MaxInlineSize default value),
 487      * which helps when add(E) is called in a C1-compiled loop.
 488      */
 489     private void add(E e, Object[] elementData, int s) {
 490         if (s == elementData.length)
 491             elementData = grow();
 492         elementData[s] = e;
 493         size = s + 1;
 494     }
 495 
 496     /**
 497      * Appends the specified element to the end of this list.
 498      *
 499      * @param e element to be appended to this list
 500      * @return {@code true} (as specified by {@link Collection#add})
 501      */
 502     public boolean add(E e) {
 503         modCount++;
 504         add(e, elementData, size);
 505         return true;
 506     }
 507 
 508     /**
 509      * Inserts the specified element at the specified position in this
 510      * list. Shifts the element currently at that position (if any) and
 511      * any subsequent elements to the right (adds one to their indices).
 512      *
 513      * @param index index at which the specified element is to be inserted
 514      * @param element element to be inserted
 515      * @throws IndexOutOfBoundsException {@inheritDoc}
 516      */
 517     public void add(int index, E element) {
 518         rangeCheckForAdd(index);
 519         modCount++;
 520         final int s;
 521         Object[] elementData;
 522         if ((s = size) == (elementData = this.elementData).length)
 523             elementData = grow();
 524         System.arraycopy(elementData, index,
 525                          elementData, index + 1,
 526                          s - index);
 527         elementData[index] = element;
 528         size = s + 1;
 529     }
 530 
 531     /**
 532      * Removes the element at the specified position in this list.
 533      * Shifts any subsequent elements to the left (subtracts one from their
 534      * indices).
 535      *
 536      * @param index the index of the element to be removed
 537      * @return the element that was removed from the list
 538      * @throws IndexOutOfBoundsException {@inheritDoc}
 539      */
 540     public E remove(int index) {
 541         Objects.checkIndex(index, size);
 542         final Object[] es = elementData;
 543 
 544         @SuppressWarnings("unchecked") E oldValue = (E) es[index];
 545         fastRemove(es, index);
 546 
 547         return oldValue;
 548     }
 549 
 550     /**
 551      * {@inheritDoc}
 552      */
 553     public boolean equals(Object o) {
 554         if (o == this) {
 555             return true;
 556         }
 557 
 558         if (!(o instanceof List)) {
 559             return false;
 560         }
 561 
 562         final int expectedModCount = modCount;
 563         // ArrayList can be subclassed and given arbitrary behavior, but we can
 564         // still deal with the common case where o is ArrayList precisely
 565         boolean equal = (o.getClass() == ArrayList.class)
 566             ? equalsArrayList((ArrayList<?>) o)
 567             : equalsRange((List<?>) o, 0, size);
 568 
 569         checkForComodification(expectedModCount);
 570         return equal;
 571     }
 572 
 573     boolean equalsRange(List<?> other, int from, int to) {
 574         final Object[] es = elementData;
 575         if (to > es.length) {
 576             throw new ConcurrentModificationException();
 577         }
 578         var oit = other.iterator();
 579         for (; from < to; from++) {
 580             if (!oit.hasNext() || !Objects.equals(es[from], oit.next())) {
 581                 return false;
 582             }
 583         }
 584         return !oit.hasNext();
 585     }
 586 
 587     private boolean equalsArrayList(ArrayList<?> other) {
 588         final int otherModCount = other.modCount;
 589         final int s = size;
 590         boolean equal;
 591         if (equal = (s == other.size)) {
 592             final Object[] otherEs = other.elementData;
 593             final Object[] es = elementData;
 594             if (s > es.length || s > otherEs.length) {
 595                 throw new ConcurrentModificationException();
 596             }
 597             for (int i = 0; i < s; i++) {
 598                 if (!Objects.equals(es[i], otherEs[i])) {
 599                     equal = false;
 600                     break;
 601                 }
 602             }
 603         }
 604         other.checkForComodification(otherModCount);
 605         return equal;
 606     }
 607 
 608     private void checkForComodification(final int expectedModCount) {
 609         if (modCount != expectedModCount) {
 610             throw new ConcurrentModificationException();
 611         }
 612     }
 613 
 614     /**
 615      * {@inheritDoc}
 616      */
 617     public int hashCode() {
 618         int expectedModCount = modCount;
 619         int hash = hashCodeRange(0, size);
 620         checkForComodification(expectedModCount);
 621         return hash;
 622     }
 623 
 624     int hashCodeRange(int from, int to) {
 625         final Object[] es = elementData;
 626         if (to > es.length) {
 627             throw new ConcurrentModificationException();
 628         }
 629         int hashCode = 1;
 630         for (int i = from; i < to; i++) {
 631             Object e = es[i];
 632             hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
 633         }
 634         return hashCode;
 635     }
 636 
 637     /**
 638      * Removes the first occurrence of the specified element from this list,
 639      * if it is present.  If the list does not contain the element, it is
 640      * unchanged.  More formally, removes the element with the lowest index
 641      * {@code i} such that
 642      * {@code Objects.equals(o, get(i))}
 643      * (if such an element exists).  Returns {@code true} if this list
 644      * contained the specified element (or equivalently, if this list
 645      * changed as a result of the call).
 646      *
 647      * @param o element to be removed from this list, if present
 648      * @return {@code true} if this list contained the specified element
 649      */
 650     public boolean remove(Object o) {
 651         final Object[] es = elementData;
 652         final int size = this.size;
 653         int i = 0;
 654         found: {
 655             if (o == null) {
 656                 for (; i < size; i++)
 657                     if (es[i] == null)
 658                         break found;
 659             } else {
 660                 for (; i < size; i++)
 661                     if (o.equals(es[i]))
 662                         break found;
 663             }
 664             return false;
 665         }
 666         fastRemove(es, i);
 667         return true;
 668     }
 669 
 670     /**
 671      * Private remove method that skips bounds checking and does not
 672      * return the value removed.
 673      */
 674     private void fastRemove(Object[] es, int i) {
 675         modCount++;
 676         final int newSize;
 677         if ((newSize = size - 1) > i)
 678             System.arraycopy(es, i + 1, es, i, newSize - i);
 679         es[size = newSize] = null;
 680     }
 681 
 682     /**
 683      * Removes all of the elements from this list.  The list will
 684      * be empty after this call returns.
 685      */
 686     public void clear() {
 687         modCount++;
 688         final Object[] es = elementData;
 689         for (int to = size, i = size = 0; i < to; i++)
 690             es[i] = null;
 691     }
 692 
 693     /**
 694      * Appends all of the elements in the specified collection to the end of
 695      * this list, in the order that they are returned by the
 696      * specified collection's Iterator.  The behavior of this operation is
 697      * undefined if the specified collection is modified while the operation
 698      * is in progress.  (This implies that the behavior of this call is
 699      * undefined if the specified collection is this list, and this
 700      * list is nonempty.)
 701      *
 702      * @param c collection containing elements to be added to this list
 703      * @return {@code true} if this list changed as a result of the call
 704      * @throws NullPointerException if the specified collection is null
 705      */
 706     public boolean addAll(Collection<? extends E> c) {
 707         Object[] a = c.toArray();
 708         modCount++;
 709         int numNew = a.length;
 710         if (numNew == 0)
 711             return false;
 712         Object[] elementData;
 713         final int s;
 714         if (numNew > (elementData = this.elementData).length - (s = size))
 715             elementData = grow(s + numNew);
 716         System.arraycopy(a, 0, elementData, s, numNew);
 717         size = s + numNew;
 718         return true;
 719     }
 720 
 721     /**
 722      * Inserts all of the elements in the specified collection into this
 723      * list, starting at the specified position.  Shifts the element
 724      * currently at that position (if any) and any subsequent elements to
 725      * the right (increases their indices).  The new elements will appear
 726      * in the list in the order that they are returned by the
 727      * specified collection's iterator.
 728      *
 729      * @param index index at which to insert the first element from the
 730      *              specified collection
 731      * @param c collection containing elements to be added to this list
 732      * @return {@code true} if this list changed as a result of the call
 733      * @throws IndexOutOfBoundsException {@inheritDoc}
 734      * @throws NullPointerException if the specified collection is null
 735      */
 736     public boolean addAll(int index, Collection<? extends E> c) {
 737         rangeCheckForAdd(index);
 738 
 739         Object[] a = c.toArray();
 740         modCount++;
 741         int numNew = a.length;
 742         if (numNew == 0)
 743             return false;
 744         Object[] elementData;
 745         final int s;
 746         if (numNew > (elementData = this.elementData).length - (s = size))
 747             elementData = grow(s + numNew);
 748 
 749         int numMoved = s - index;
 750         if (numMoved > 0)
 751             System.arraycopy(elementData, index,
 752                              elementData, index + numNew,
 753                              numMoved);
 754         System.arraycopy(a, 0, elementData, index, numNew);
 755         size = s + numNew;
 756         return true;
 757     }
 758 
 759     /**
 760      * Removes from this list all of the elements whose index is between
 761      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
 762      * Shifts any succeeding elements to the left (reduces their index).
 763      * This call shortens the list by {@code (toIndex - fromIndex)} elements.
 764      * (If {@code toIndex==fromIndex}, this operation has no effect.)
 765      *
 766      * @throws IndexOutOfBoundsException if {@code fromIndex} or
 767      *         {@code toIndex} is out of range
 768      *         ({@code fromIndex < 0 ||
 769      *          toIndex > size() ||
 770      *          toIndex < fromIndex})
 771      */
 772     protected void removeRange(int fromIndex, int toIndex) {
 773         if (fromIndex > toIndex) {
 774             throw new IndexOutOfBoundsException(
 775                     outOfBoundsMsg(fromIndex, toIndex));
 776         }
 777         modCount++;
 778         shiftTailOverGap(elementData, fromIndex, toIndex);
 779     }
 780 
 781     /** Erases the gap from lo to hi, by sliding down following elements. */
 782     private void shiftTailOverGap(Object[] es, int lo, int hi) {
 783         System.arraycopy(es, hi, es, lo, size - hi);
 784         for (int to = size, i = (size -= hi - lo); i < to; i++)
 785             es[i] = null;
 786     }
 787 
 788     /**
 789      * A version of rangeCheck used by add and addAll.
 790      */
 791     private void rangeCheckForAdd(int index) {
 792         if (index > size || index < 0)
 793             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 794     }
 795 
 796     /**
 797      * Constructs an IndexOutOfBoundsException detail message.
 798      * Of the many possible refactorings of the error handling code,
 799      * this "outlining" performs best with both server and client VMs.
 800      */
 801     private String outOfBoundsMsg(int index) {
 802         return "Index: "+index+", Size: "+size;
 803     }
 804 
 805     /**
 806      * A version used in checking (fromIndex > toIndex) condition
 807      */
 808     private static String outOfBoundsMsg(int fromIndex, int toIndex) {
 809         return "From Index: " + fromIndex + " > To Index: " + toIndex;
 810     }
 811 
 812     /**
 813      * Removes from this list all of its elements that are contained in the
 814      * specified collection.
 815      *
 816      * @param c collection containing elements to be removed from this list
 817      * @return {@code true} if this list changed as a result of the call
 818      * @throws ClassCastException if the class of an element of this list
 819      *         is incompatible with the specified collection
 820      * (<a href="Collection.html#optional-restrictions">optional</a>)
 821      * @throws NullPointerException if this list contains a null element and the
 822      *         specified collection does not permit null elements
 823      * (<a href="Collection.html#optional-restrictions">optional</a>),
 824      *         or if the specified collection is null
 825      * @see Collection#contains(Object)
 826      */
 827     public boolean removeAll(Collection<?> c) {
 828         return batchRemove(c, false, 0, size);
 829     }
 830 
 831     /**
 832      * Retains only the elements in this list that are contained in the
 833      * specified collection.  In other words, removes from this list all
 834      * of its elements that are not contained in the specified collection.
 835      *
 836      * @param c collection containing elements to be retained in this list
 837      * @return {@code true} if this list changed as a result of the call
 838      * @throws ClassCastException if the class of an element of this list
 839      *         is incompatible with the specified collection
 840      * (<a href="Collection.html#optional-restrictions">optional</a>)
 841      * @throws NullPointerException if this list contains a null element and the
 842      *         specified collection does not permit null elements
 843      * (<a href="Collection.html#optional-restrictions">optional</a>),
 844      *         or if the specified collection is null
 845      * @see Collection#contains(Object)
 846      */
 847     public boolean retainAll(Collection<?> c) {
 848         return batchRemove(c, true, 0, size);
 849     }
 850 
 851     boolean batchRemove(Collection<?> c, boolean complement,
 852                         final int from, final int end) {
 853         Objects.requireNonNull(c);
 854         final Object[] es = elementData;
 855         int r;
 856         // Optimize for initial run of survivors
 857         for (r = from;; r++) {
 858             if (r == end)
 859                 return false;
 860             if (c.contains(es[r]) != complement)
 861                 break;
 862         }
 863         int w = r++;
 864         try {
 865             for (Object e; r < end; r++)
 866                 if (c.contains(e = es[r]) == complement)
 867                     es[w++] = e;
 868         } catch (Throwable ex) {
 869             // Preserve behavioral compatibility with AbstractCollection,
 870             // even if c.contains() throws.
 871             System.arraycopy(es, r, es, w, end - r);
 872             w += end - r;
 873             throw ex;
 874         } finally {
 875             modCount += end - w;
 876             shiftTailOverGap(es, w, end);
 877         }
 878         return true;
 879     }
 880 
 881     /**
 882      * Saves the state of the {@code ArrayList} instance to a stream
 883      * (that is, serializes it).
 884      *
 885      * @param s the stream
 886      * @throws java.io.IOException if an I/O error occurs
 887      * @serialData The length of the array backing the {@code ArrayList}
 888      *             instance is emitted (int), followed by all of its elements
 889      *             (each an {@code Object}) in the proper order.
 890      */
 891     private void writeObject(java.io.ObjectOutputStream s)
 892         throws java.io.IOException {
 893         // Write out element count, and any hidden stuff
 894         int expectedModCount = modCount;
 895         s.defaultWriteObject();
 896 
 897         // Write out size as capacity for behavioral compatibility with clone()
 898         s.writeInt(size);
 899 
 900         // Write out all elements in the proper order.
 901         for (int i=0; i<size; i++) {
 902             s.writeObject(elementData[i]);
 903         }
 904 
 905         if (modCount != expectedModCount) {
 906             throw new ConcurrentModificationException();
 907         }
 908     }
 909 
 910     /**
 911      * Reconstitutes the {@code ArrayList} instance from a stream (that is,
 912      * deserializes it).
 913      * @param s the stream
 914      * @throws ClassNotFoundException if the class of a serialized object
 915      *         could not be found
 916      * @throws java.io.IOException if an I/O error occurs
 917      */
 918     private void readObject(java.io.ObjectInputStream s)
 919         throws java.io.IOException, ClassNotFoundException {
 920 
 921         // Read in size, and any hidden stuff
 922         s.defaultReadObject();
 923 
 924         // Read in capacity
 925         s.readInt(); // ignored
 926 
 927         if (size > 0) {
 928             // like clone(), allocate array based upon size not capacity
 929             SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);
 930             Object[] elements = new Object[size];
 931 
 932             // Read in all elements in the proper order.
 933             for (int i = 0; i < size; i++) {
 934                 elements[i] = s.readObject();
 935             }
 936 
 937             elementData = elements;
 938         } else if (size == 0) {
 939             elementData = EMPTY_ELEMENTDATA;
 940         } else {
 941             throw new java.io.InvalidObjectException("Invalid size: " + size);
 942         }
 943     }
 944 
 945     /**
 946      * Returns a list iterator over the elements in this list (in proper
 947      * sequence), starting at the specified position in the list.
 948      * The specified index indicates the first element that would be
 949      * returned by an initial call to {@link ListIterator#next next}.
 950      * An initial call to {@link ListIterator#previous previous} would
 951      * return the element with the specified index minus one.
 952      *
 953      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 954      *
 955      * @throws IndexOutOfBoundsException {@inheritDoc}
 956      */
 957     public ListIterator<E> listIterator(int index) {
 958         rangeCheckForAdd(index);
 959         return new ListItr(index);
 960     }
 961 
 962     /**
 963      * Returns a list iterator over the elements in this list (in proper
 964      * sequence).
 965      *
 966      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 967      *
 968      * @see #listIterator(int)
 969      */
 970     public ListIterator<E> listIterator() {
 971         return new ListItr(0);
 972     }
 973 
 974     /**
 975      * Returns an iterator over the elements in this list in proper sequence.
 976      *
 977      * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 978      *
 979      * @return an iterator over the elements in this list in proper sequence
 980      */
 981     public Iterator<E> iterator() {
 982         return new Itr();
 983     }
 984 
 985     /**
 986      * An optimized version of AbstractList.Itr
 987      */
 988     private class Itr implements Iterator<E> {
 989         int cursor;       // index of next element to return
 990         int lastRet = -1; // index of last element returned; -1 if no such
 991         int expectedModCount = modCount;
 992 
 993         // prevent creating a synthetic constructor
 994         Itr() {}
 995 
 996         public boolean hasNext() {
 997             return cursor != size;
 998         }
 999 
1000         @SuppressWarnings("unchecked")
1001         public E next() {
1002             checkForComodification();
1003             int i = cursor;
1004             if (i >= size)
1005                 throw new NoSuchElementException();
1006             Object[] elementData = ArrayList.this.elementData;
1007             if (i >= elementData.length)
1008                 throw new ConcurrentModificationException();
1009             cursor = i + 1;
1010             return (E) elementData[lastRet = i];
1011         }
1012 
1013         public void remove() {
1014             if (lastRet < 0)
1015                 throw new IllegalStateException();
1016             checkForComodification();
1017 
1018             try {
1019                 ArrayList.this.remove(lastRet);
1020                 cursor = lastRet;
1021                 lastRet = -1;
1022                 expectedModCount = modCount;
1023             } catch (IndexOutOfBoundsException ex) {
1024                 throw new ConcurrentModificationException();
1025             }
1026         }
1027 
1028         @Override
1029         public void forEachRemaining(Consumer<? super E> action) {
1030             Objects.requireNonNull(action);
1031             final int size = ArrayList.this.size;
1032             int i = cursor;
1033             if (i < size) {
1034                 final Object[] es = elementData;
1035                 if (i >= es.length)
1036                     throw new ConcurrentModificationException();
1037                 for (; i < size && modCount == expectedModCount; i++)
1038                     action.accept(elementAt(es, i));
1039                 // update once at end to reduce heap write traffic
1040                 cursor = i;
1041                 lastRet = i - 1;
1042                 checkForComodification();
1043             }
1044         }
1045 
1046         final void checkForComodification() {
1047             if (modCount != expectedModCount)
1048                 throw new ConcurrentModificationException();
1049         }
1050     }
1051 
1052     /**
1053      * An optimized version of AbstractList.ListItr
1054      */
1055     private class ListItr extends Itr implements ListIterator<E> {
1056         ListItr(int index) {
1057             super();
1058             cursor = index;
1059         }
1060 
1061         public boolean hasPrevious() {
1062             return cursor != 0;
1063         }
1064 
1065         public int nextIndex() {
1066             return cursor;
1067         }
1068 
1069         public int previousIndex() {
1070             return cursor - 1;
1071         }
1072 
1073         @SuppressWarnings("unchecked")
1074         public E previous() {
1075             checkForComodification();
1076             int i = cursor - 1;
1077             if (i < 0)
1078                 throw new NoSuchElementException();
1079             Object[] elementData = ArrayList.this.elementData;
1080             if (i >= elementData.length)
1081                 throw new ConcurrentModificationException();
1082             cursor = i;
1083             return (E) elementData[lastRet = i];
1084         }
1085 
1086         public void set(E e) {
1087             if (lastRet < 0)
1088                 throw new IllegalStateException();
1089             checkForComodification();
1090 
1091             try {
1092                 ArrayList.this.set(lastRet, e);
1093             } catch (IndexOutOfBoundsException ex) {
1094                 throw new ConcurrentModificationException();
1095             }
1096         }
1097 
1098         public void add(E e) {
1099             checkForComodification();
1100 
1101             try {
1102                 int i = cursor;
1103                 ArrayList.this.add(i, e);
1104                 cursor = i + 1;
1105                 lastRet = -1;
1106                 expectedModCount = modCount;
1107             } catch (IndexOutOfBoundsException ex) {
1108                 throw new ConcurrentModificationException();
1109             }
1110         }
1111     }
1112 
1113     /**
1114      * Returns a view of the portion of this list between the specified
1115      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.  (If
1116      * {@code fromIndex} and {@code toIndex} are equal, the returned list is
1117      * empty.)  The returned list is backed by this list, so non-structural
1118      * changes in the returned list are reflected in this list, and vice-versa.
1119      * The returned list supports all of the optional list operations.
1120      *
1121      * <p>This method eliminates the need for explicit range operations (of
1122      * the sort that commonly exist for arrays).  Any operation that expects
1123      * a list can be used as a range operation by passing a subList view
1124      * instead of a whole list.  For example, the following idiom
1125      * removes a range of elements from a list:
1126      * <pre>
1127      *      list.subList(from, to).clear();
1128      * </pre>
1129      * Similar idioms may be constructed for {@link #indexOf(Object)} and
1130      * {@link #lastIndexOf(Object)}, and all of the algorithms in the
1131      * {@link Collections} class can be applied to a subList.
1132      *
1133      * <p>The semantics of the list returned by this method become undefined if
1134      * the backing list (i.e., this list) is <i>structurally modified</i> in
1135      * any way other than via the returned list.  (Structural modifications are
1136      * those that change the size of this list, or otherwise perturb it in such
1137      * a fashion that iterations in progress may yield incorrect results.)
1138      *
1139      * @throws IndexOutOfBoundsException {@inheritDoc}
1140      * @throws IllegalArgumentException {@inheritDoc}
1141      */
1142     public List<E> subList(int fromIndex, int toIndex) {
1143         subListRangeCheck(fromIndex, toIndex, size);
1144         return new SubList<>(this, fromIndex, toIndex);
1145     }
1146 
1147     private static class SubList<E> extends AbstractList<E> implements RandomAccess {
1148         private final ArrayList<E> root;
1149         private final SubList<E> parent;
1150         private final int offset;
1151         private int size;
1152 
1153         /**
1154          * Constructs a sublist of an arbitrary ArrayList.
1155          */
1156         public SubList(ArrayList<E> root, int fromIndex, int toIndex) {
1157             this.root = root;
1158             this.parent = null;
1159             this.offset = fromIndex;
1160             this.size = toIndex - fromIndex;
1161             this.modCount = root.modCount;
1162         }
1163 
1164         /**
1165          * Constructs a sublist of another SubList.
1166          */
1167         private SubList(SubList<E> parent, int fromIndex, int toIndex) {
1168             this.root = parent.root;
1169             this.parent = parent;
1170             this.offset = parent.offset + fromIndex;
1171             this.size = toIndex - fromIndex;
1172             this.modCount = root.modCount;
1173         }
1174 
1175         public E set(int index, E element) {
1176             Objects.checkIndex(index, size);
1177             checkForComodification();
1178             E oldValue = root.elementData(offset + index);
1179             root.elementData[offset + index] = element;
1180             return oldValue;
1181         }
1182 
1183         public E get(int index) {
1184             Objects.checkIndex(index, size);
1185             checkForComodification();
1186             return root.elementData(offset + index);
1187         }
1188 
1189         public int size() {
1190             checkForComodification();
1191             return size;
1192         }
1193 
1194         public void add(int index, E element) {
1195             rangeCheckForAdd(index);
1196             checkForComodification();
1197             root.add(offset + index, element);
1198             updateSizeAndModCount(1);
1199         }
1200 
1201         public E remove(int index) {
1202             Objects.checkIndex(index, size);
1203             checkForComodification();
1204             E result = root.remove(offset + index);
1205             updateSizeAndModCount(-1);
1206             return result;
1207         }
1208 
1209         protected void removeRange(int fromIndex, int toIndex) {
1210             checkForComodification();
1211             root.removeRange(offset + fromIndex, offset + toIndex);
1212             updateSizeAndModCount(fromIndex - toIndex);
1213         }
1214 
1215         public boolean addAll(Collection<? extends E> c) {
1216             return addAll(this.size, c);
1217         }
1218 
1219         public boolean addAll(int index, Collection<? extends E> c) {
1220             rangeCheckForAdd(index);
1221             int cSize = c.size();
1222             if (cSize==0)
1223                 return false;
1224             checkForComodification();
1225             root.addAll(offset + index, c);
1226             updateSizeAndModCount(cSize);
1227             return true;
1228         }
1229 
1230         public void replaceAll(UnaryOperator<E> operator) {
1231             root.replaceAllRange(operator, offset, offset + size);
1232         }
1233 
1234         public boolean removeAll(Collection<?> c) {
1235             return batchRemove(c, false);
1236         }
1237 
1238         public boolean retainAll(Collection<?> c) {
1239             return batchRemove(c, true);
1240         }
1241 
1242         private boolean batchRemove(Collection<?> c, boolean complement) {
1243             checkForComodification();
1244             int oldSize = root.size;
1245             boolean modified =
1246                 root.batchRemove(c, complement, offset, offset + size);
1247             if (modified)
1248                 updateSizeAndModCount(root.size - oldSize);
1249             return modified;
1250         }
1251 
1252         public boolean removeIf(Predicate<? super E> filter) {
1253             checkForComodification();
1254             int oldSize = root.size;
1255             boolean modified = root.removeIf(filter, offset, offset + size);
1256             if (modified)
1257                 updateSizeAndModCount(root.size - oldSize);
1258             return modified;
1259         }
1260 
1261         public Object[] toArray() {
1262             checkForComodification();
1263             return Arrays.copyOfRange(root.elementData, offset, offset + size);
1264         }
1265 
1266         @SuppressWarnings("unchecked")
1267         public <T> T[] toArray(T[] a) {
1268             checkForComodification();
1269             if (a.length < size)
1270                 return (T[]) Arrays.copyOfRange(
1271                         root.elementData, offset, offset + size, a.getClass());
1272             System.arraycopy(root.elementData, offset, a, 0, size);
1273             if (a.length > size)
1274                 a[size] = null;
1275             return a;
1276         }
1277 
1278         public boolean equals(Object o) {
1279             if (o == this) {
1280                 return true;
1281             }
1282 
1283             if (!(o instanceof List)) {
1284                 return false;
1285             }
1286 
1287             boolean equal = root.equalsRange((List<?>)o, offset, offset + size);
1288             checkForComodification();
1289             return equal;
1290         }
1291 
1292         public int hashCode() {
1293             int hash = root.hashCodeRange(offset, offset + size);
1294             checkForComodification();
1295             return hash;
1296         }
1297 
1298         public int indexOf(Object o) {
1299             int index = root.indexOfRange(o, offset, offset + size);
1300             checkForComodification();
1301             return index >= 0 ? index - offset : -1;
1302         }
1303 
1304         public int lastIndexOf(Object o) {
1305             int index = root.lastIndexOfRange(o, offset, offset + size);
1306             checkForComodification();
1307             return index >= 0 ? index - offset : -1;
1308         }
1309 
1310         public boolean contains(Object o) {
1311             return indexOf(o) >= 0;
1312         }
1313 
1314         public Iterator<E> iterator() {
1315             return listIterator();
1316         }
1317 
1318         public ListIterator<E> listIterator(int index) {
1319             checkForComodification();
1320             rangeCheckForAdd(index);
1321 
1322             return new ListIterator<E>() {
1323                 int cursor = index;
1324                 int lastRet = -1;
1325                 int expectedModCount = root.modCount;
1326 
1327                 public boolean hasNext() {
1328                     return cursor != SubList.this.size;
1329                 }
1330 
1331                 @SuppressWarnings("unchecked")
1332                 public E next() {
1333                     checkForComodification();
1334                     int i = cursor;
1335                     if (i >= SubList.this.size)
1336                         throw new NoSuchElementException();
1337                     Object[] elementData = root.elementData;
1338                     if (offset + i >= elementData.length)
1339                         throw new ConcurrentModificationException();
1340                     cursor = i + 1;
1341                     return (E) elementData[offset + (lastRet = i)];
1342                 }
1343 
1344                 public boolean hasPrevious() {
1345                     return cursor != 0;
1346                 }
1347 
1348                 @SuppressWarnings("unchecked")
1349                 public E previous() {
1350                     checkForComodification();
1351                     int i = cursor - 1;
1352                     if (i < 0)
1353                         throw new NoSuchElementException();
1354                     Object[] elementData = root.elementData;
1355                     if (offset + i >= elementData.length)
1356                         throw new ConcurrentModificationException();
1357                     cursor = i;
1358                     return (E) elementData[offset + (lastRet = i)];
1359                 }
1360 
1361                 public void forEachRemaining(Consumer<? super E> action) {
1362                     Objects.requireNonNull(action);
1363                     final int size = SubList.this.size;
1364                     int i = cursor;
1365                     if (i < size) {
1366                         final Object[] es = root.elementData;
1367                         if (offset + i >= es.length)
1368                             throw new ConcurrentModificationException();
1369                         for (; i < size && modCount == expectedModCount; i++)
1370                             action.accept(elementAt(es, offset + i));
1371                         // update once at end to reduce heap write traffic
1372                         cursor = i;
1373                         lastRet = i - 1;
1374                         checkForComodification();
1375                     }
1376                 }
1377 
1378                 public int nextIndex() {
1379                     return cursor;
1380                 }
1381 
1382                 public int previousIndex() {
1383                     return cursor - 1;
1384                 }
1385 
1386                 public void remove() {
1387                     if (lastRet < 0)
1388                         throw new IllegalStateException();
1389                     checkForComodification();
1390 
1391                     try {
1392                         SubList.this.remove(lastRet);
1393                         cursor = lastRet;
1394                         lastRet = -1;
1395                         expectedModCount = root.modCount;
1396                     } catch (IndexOutOfBoundsException ex) {
1397                         throw new ConcurrentModificationException();
1398                     }
1399                 }
1400 
1401                 public void set(E e) {
1402                     if (lastRet < 0)
1403                         throw new IllegalStateException();
1404                     checkForComodification();
1405 
1406                     try {
1407                         root.set(offset + lastRet, e);
1408                     } catch (IndexOutOfBoundsException ex) {
1409                         throw new ConcurrentModificationException();
1410                     }
1411                 }
1412 
1413                 public void add(E e) {
1414                     checkForComodification();
1415 
1416                     try {
1417                         int i = cursor;
1418                         SubList.this.add(i, e);
1419                         cursor = i + 1;
1420                         lastRet = -1;
1421                         expectedModCount = root.modCount;
1422                     } catch (IndexOutOfBoundsException ex) {
1423                         throw new ConcurrentModificationException();
1424                     }
1425                 }
1426 
1427                 final void checkForComodification() {
1428                     if (root.modCount != expectedModCount)
1429                         throw new ConcurrentModificationException();
1430                 }
1431             };
1432         }
1433 
1434         public List<E> subList(int fromIndex, int toIndex) {
1435             subListRangeCheck(fromIndex, toIndex, size);
1436             return new SubList<>(this, fromIndex, toIndex);
1437         }
1438 
1439         private void rangeCheckForAdd(int index) {
1440             if (index < 0 || index > this.size)
1441                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1442         }
1443 
1444         private String outOfBoundsMsg(int index) {
1445             return "Index: "+index+", Size: "+this.size;
1446         }
1447 
1448         private void checkForComodification() {
1449             if (root.modCount != modCount)
1450                 throw new ConcurrentModificationException();
1451         }
1452 
1453         private void updateSizeAndModCount(int sizeChange) {
1454             SubList<E> slist = this;
1455             do {
1456                 slist.size += sizeChange;
1457                 slist.modCount = root.modCount;
1458                 slist = slist.parent;
1459             } while (slist != null);
1460         }
1461 
1462         public Spliterator<E> spliterator() {
1463             checkForComodification();
1464 
1465             // ArrayListSpliterator not used here due to late-binding
1466             return new Spliterator<E>() {
1467                 private int index = offset; // current index, modified on advance/split
1468                 private int fence = -1; // -1 until used; then one past last index
1469                 private int expectedModCount; // initialized when fence set
1470 
1471                 private int getFence() { // initialize fence to size on first use
1472                     int hi; // (a specialized variant appears in method forEach)
1473                     if ((hi = fence) < 0) {
1474                         expectedModCount = modCount;
1475                         hi = fence = offset + size;
1476                     }
1477                     return hi;
1478                 }
1479 
1480                 public ArrayList<E>.ArrayListSpliterator trySplit() {
1481                     int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1482                     // ArrayListSpliterator can be used here as the source is already bound
1483                     return (lo >= mid) ? null : // divide range in half unless too small
1484                         root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
1485                 }
1486 
1487                 public boolean tryAdvance(Consumer<? super E> action) {
1488                     Objects.requireNonNull(action);
1489                     int hi = getFence(), i = index;
1490                     if (i < hi) {
1491                         index = i + 1;
1492                         @SuppressWarnings("unchecked") E e = (E)root.elementData[i];
1493                         action.accept(e);
1494                         if (root.modCount != expectedModCount)
1495                             throw new ConcurrentModificationException();
1496                         return true;
1497                     }
1498                     return false;
1499                 }
1500 
1501                 public void forEachRemaining(Consumer<? super E> action) {
1502                     Objects.requireNonNull(action);
1503                     int i, hi, mc; // hoist accesses and checks from loop
1504                     ArrayList<E> lst = root;
1505                     Object[] a;
1506                     if ((a = lst.elementData) != null) {
1507                         if ((hi = fence) < 0) {
1508                             mc = modCount;
1509                             hi = offset + size;
1510                         }
1511                         else
1512                             mc = expectedModCount;
1513                         if ((i = index) >= 0 && (index = hi) <= a.length) {
1514                             for (; i < hi; ++i) {
1515                                 @SuppressWarnings("unchecked") E e = (E) a[i];
1516                                 action.accept(e);
1517                             }
1518                             if (lst.modCount == mc)
1519                                 return;
1520                         }
1521                     }
1522                     throw new ConcurrentModificationException();
1523                 }
1524 
1525                 public long estimateSize() {
1526                     return getFence() - index;
1527                 }
1528 
1529                 public int characteristics() {
1530                     return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1531                 }
1532             };
1533         }
1534     }
1535 
1536     /**
1537      * @throws NullPointerException {@inheritDoc}
1538      */
1539     @Override
1540     public void forEach(Consumer<? super E> action) {
1541         Objects.requireNonNull(action);
1542         final int expectedModCount = modCount;
1543         final Object[] es = elementData;
1544         final int size = this.size;
1545         for (int i = 0; modCount == expectedModCount && i < size; i++)
1546             action.accept(elementAt(es, i));
1547         if (modCount != expectedModCount)
1548             throw new ConcurrentModificationException();
1549     }
1550 
1551     /**
1552      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1553      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1554      * list.
1555      *
1556      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1557      * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1558      * Overriding implementations should document the reporting of additional
1559      * characteristic values.
1560      *
1561      * @return a {@code Spliterator} over the elements in this list
1562      * @since 1.8
1563      */
1564     @Override
1565     public Spliterator<E> spliterator() {
1566         return new ArrayListSpliterator(0, -1, 0);
1567     }
1568 
1569     /** Index-based split-by-two, lazily initialized Spliterator */
1570     final class ArrayListSpliterator implements Spliterator<E> {
1571 
1572         /*
1573          * If ArrayLists were immutable, or structurally immutable (no
1574          * adds, removes, etc), we could implement their spliterators
1575          * with Arrays.spliterator. Instead we detect as much
1576          * interference during traversal as practical without
1577          * sacrificing much performance. We rely primarily on
1578          * modCounts. These are not guaranteed to detect concurrency
1579          * violations, and are sometimes overly conservative about
1580          * within-thread interference, but detect enough problems to
1581          * be worthwhile in practice. To carry this out, we (1) lazily
1582          * initialize fence and expectedModCount until the latest
1583          * point that we need to commit to the state we are checking
1584          * against; thus improving precision.  (This doesn't apply to
1585          * SubLists, that create spliterators with current non-lazy
1586          * values).  (2) We perform only a single
1587          * ConcurrentModificationException check at the end of forEach
1588          * (the most performance-sensitive method). When using forEach
1589          * (as opposed to iterators), we can normally only detect
1590          * interference after actions, not before. Further
1591          * CME-triggering checks apply to all other possible
1592          * violations of assumptions for example null or too-small
1593          * elementData array given its size(), that could only have
1594          * occurred due to interference.  This allows the inner loop
1595          * of forEach to run without any further checks, and
1596          * simplifies lambda-resolution. While this does entail a
1597          * number of checks, note that in the common case of
1598          * list.stream().forEach(a), no checks or other computation
1599          * occur anywhere other than inside forEach itself.  The other
1600          * less-often-used methods cannot take advantage of most of
1601          * these streamlinings.
1602          */
1603 
1604         private int index; // current index, modified on advance/split
1605         private int fence; // -1 until used; then one past last index
1606         private int expectedModCount; // initialized when fence set
1607 
1608         /** Creates new spliterator covering the given range. */
1609         ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1610             this.index = origin;
1611             this.fence = fence;
1612             this.expectedModCount = expectedModCount;
1613         }
1614 
1615         private int getFence() { // initialize fence to size on first use
1616             int hi; // (a specialized variant appears in method forEach)
1617             if ((hi = fence) < 0) {
1618                 expectedModCount = modCount;
1619                 hi = fence = size;
1620             }
1621             return hi;
1622         }
1623 
1624         public ArrayListSpliterator trySplit() {
1625             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1626             return (lo >= mid) ? null : // divide range in half unless too small
1627                 new ArrayListSpliterator(lo, index = mid, expectedModCount);
1628         }
1629 
1630         public boolean tryAdvance(Consumer<? super E> action) {
1631             if (action == null)
1632                 throw new NullPointerException();
1633             int hi = getFence(), i = index;
1634             if (i < hi) {
1635                 index = i + 1;
1636                 @SuppressWarnings("unchecked") E e = (E)elementData[i];
1637                 action.accept(e);
1638                 if (modCount != expectedModCount)
1639                     throw new ConcurrentModificationException();
1640                 return true;
1641             }
1642             return false;
1643         }
1644 
1645         public void forEachRemaining(Consumer<? super E> action) {
1646             int i, hi, mc; // hoist accesses and checks from loop
1647             Object[] a;
1648             if (action == null)
1649                 throw new NullPointerException();
1650             if ((a = elementData) != null) {
1651                 if ((hi = fence) < 0) {
1652                     mc = modCount;
1653                     hi = size;
1654                 }
1655                 else
1656                     mc = expectedModCount;
1657                 if ((i = index) >= 0 && (index = hi) <= a.length) {
1658                     for (; i < hi; ++i) {
1659                         @SuppressWarnings("unchecked") E e = (E) a[i];
1660                         action.accept(e);
1661                     }
1662                     if (modCount == mc)
1663                         return;
1664                 }
1665             }
1666             throw new ConcurrentModificationException();
1667         }
1668 
1669         public long estimateSize() {
1670             return getFence() - index;
1671         }
1672 
1673         public int characteristics() {
1674             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1675         }
1676     }
1677 
1678     // A tiny bit set implementation
1679 
1680     private static long[] nBits(int n) {
1681         return new long[((n - 1) >> 6) + 1];
1682     }
1683     private static void setBit(long[] bits, int i) {
1684         bits[i >> 6] |= 1L << i;
1685     }
1686     private static boolean isClear(long[] bits, int i) {
1687         return (bits[i >> 6] & (1L << i)) == 0;
1688     }
1689 
1690     /**
1691      * @throws NullPointerException {@inheritDoc}
1692      */
1693     @Override
1694     public boolean removeIf(Predicate<? super E> filter) {
1695         return removeIf(filter, 0, size);
1696     }
1697 
1698     /**
1699      * Removes all elements satisfying the given predicate, from index
1700      * i (inclusive) to index end (exclusive).
1701      */
1702     boolean removeIf(Predicate<? super E> filter, int i, final int end) {
1703         Objects.requireNonNull(filter);
1704         int expectedModCount = modCount;
1705         final Object[] es = elementData;
1706         // Optimize for initial run of survivors
1707         for (; i < end && !filter.test(elementAt(es, i)); i++)
1708             ;
1709         // Tolerate predicates that reentrantly access the collection for
1710         // read (but writers still get CME), so traverse once to find
1711         // elements to delete, a second pass to physically expunge.
1712         if (i < end) {
1713             final int beg = i;
1714             final long[] deathRow = nBits(end - beg);
1715             deathRow[0] = 1L;   // set bit 0
1716             for (i = beg + 1; i < end; i++)
1717                 if (filter.test(elementAt(es, i)))
1718                     setBit(deathRow, i - beg);
1719             if (modCount != expectedModCount)
1720                 throw new ConcurrentModificationException();
1721             modCount++;
1722             int w = beg;
1723             for (i = beg; i < end; i++)
1724                 if (isClear(deathRow, i - beg))
1725                     es[w++] = es[i];
1726             shiftTailOverGap(es, w, end);
1727             return true;
1728         } else {
1729             if (modCount != expectedModCount)
1730                 throw new ConcurrentModificationException();
1731             return false;
1732         }
1733     }
1734 
1735     @Override
1736     public void replaceAll(UnaryOperator<E> operator) {
1737         replaceAllRange(operator, 0, size);
1738         modCount++;
1739     }
1740 
1741     private void replaceAllRange(UnaryOperator<E> operator, int i, int end) {
1742         Objects.requireNonNull(operator);
1743         final int expectedModCount = modCount;
1744         final Object[] es = elementData;
1745         for (; modCount == expectedModCount && i < end; i++)
1746             es[i] = operator.apply(elementAt(es, i));
1747         if (modCount != expectedModCount)
1748             throw new ConcurrentModificationException();
1749     }
1750 
1751     @Override
1752     @SuppressWarnings("unchecked")
1753     public void sort(Comparator<? super E> c) {
1754         final int expectedModCount = modCount;
1755         Arrays.sort((E[]) elementData, 0, size, c);
1756         if (modCount != expectedModCount)
1757             throw new ConcurrentModificationException();
1758         modCount++;
1759     }
1760 
1761     void checkInvariants() {
1762         // assert size >= 0;
1763         // assert size == elementData.length || elementData[size] == null;
1764     }
1765 }