1 /*
   2  * Copyright (c) 1997, 2017, 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.misc.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/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         elementData = c.toArray();
 180         if ((size = elementData.length) != 0) {
 181             // defend against c.toArray (incorrectly) not returning Object[]
 182             // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
 183             if (elementData.getClass() != Object[].class)
 184                 elementData = Arrays.copyOf(elementData, size, Object[].class);
 185         } else {
 186             // replace with empty array.
 187             this.elementData = EMPTY_ELEMENTDATA;
 188         }
 189     }
 190 
 191     /**
 192      * Trims the capacity of this {@code ArrayList} instance to be the
 193      * list's current size.  An application can use this operation to minimize
 194      * the storage of an {@code ArrayList} instance.
 195      */
 196     public void trimToSize() {
 197         modCount++;
 198         if (size < elementData.length) {
 199             elementData = (size == 0)
 200               ? EMPTY_ELEMENTDATA
 201               : Arrays.copyOf(elementData, size);
 202         }
 203     }
 204 
 205     /**
 206      * Increases the capacity of this {@code ArrayList} instance, if
 207      * necessary, to ensure that it can hold at least the number of elements
 208      * specified by the minimum capacity argument.
 209      *
 210      * @param minCapacity the desired minimum capacity
 211      */
 212     public void ensureCapacity(int minCapacity) {
 213         if (minCapacity > elementData.length
 214             && !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 215                  && minCapacity <= DEFAULT_CAPACITY)) {
 216             modCount++;
 217             grow(minCapacity);
 218         }
 219     }
 220 
 221     /**
 222      * The maximum size of array to allocate (unless necessary).
 223      * Some VMs reserve some header words in an array.
 224      * Attempts to allocate larger arrays may result in
 225      * OutOfMemoryError: Requested array size exceeds VM limit
 226      */
 227     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 228 
 229     /**
 230      * Increases the capacity to ensure that it can hold at least the
 231      * number of elements specified by the minimum capacity argument.
 232      *
 233      * @param minCapacity the desired minimum capacity
 234      * @throws OutOfMemoryError if minCapacity is less than zero
 235      */
 236     private Object[] grow(int minCapacity) {
 237         return elementData = Arrays.copyOf(elementData,
 238                                            newCapacity(minCapacity));
 239     }
 240 
 241     private Object[] grow() {
 242         return grow(size + 1);
 243     }
 244 
 245     /**
 246      * Returns a capacity at least as large as the given minimum capacity.
 247      * Returns the current capacity increased by 50% if that suffices.
 248      * Will not return a capacity greater than MAX_ARRAY_SIZE unless
 249      * the given minimum capacity is greater than MAX_ARRAY_SIZE.
 250      *
 251      * @param minCapacity the desired minimum capacity
 252      * @throws OutOfMemoryError if minCapacity is less than zero
 253      */
 254     private int newCapacity(int minCapacity) {
 255         // overflow-conscious code
 256         int oldCapacity = elementData.length;
 257         int newCapacity = oldCapacity + (oldCapacity >> 1);
 258         if (newCapacity - minCapacity <= 0) {
 259             if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
 260                 return Math.max(DEFAULT_CAPACITY, minCapacity);
 261             if (minCapacity < 0) // overflow
 262                 throw new OutOfMemoryError();
 263             return minCapacity;
 264         }
 265         return (newCapacity - MAX_ARRAY_SIZE <= 0)
 266             ? newCapacity
 267             : hugeCapacity(minCapacity);
 268     }
 269 
 270     private static int hugeCapacity(int minCapacity) {
 271         if (minCapacity < 0) // overflow
 272             throw new OutOfMemoryError();
 273         return (minCapacity > MAX_ARRAY_SIZE)
 274             ? Integer.MAX_VALUE
 275             : MAX_ARRAY_SIZE;
 276     }
 277 
 278     /**
 279      * Returns the number of elements in this list.
 280      *
 281      * @return the number of elements in this list
 282      */
 283     public int size() {
 284         return size;
 285     }
 286 
 287     /**
 288      * Returns {@code true} if this list contains no elements.
 289      *
 290      * @return {@code true} if this list contains no elements
 291      */
 292     public boolean isEmpty() {
 293         return size == 0;
 294     }
 295 
 296     /**
 297      * Returns {@code true} if this list contains the specified element.
 298      * More formally, returns {@code true} if and only if this list contains
 299      * at least one element {@code e} such that
 300      * {@code Objects.equals(o, e)}.
 301      *
 302      * @param o element whose presence in this list is to be tested
 303      * @return {@code true} if this list contains the specified element
 304      */
 305     public boolean contains(Object o) {
 306         return indexOf(o) >= 0;
 307     }
 308 
 309     /**
 310      * Returns the index of the first occurrence of the specified element
 311      * in this list, or -1 if this list does not contain the element.
 312      * More formally, returns the lowest index {@code i} such that
 313      * {@code Objects.equals(o, get(i))},
 314      * or -1 if there is no such index.
 315      */
 316     public int indexOf(Object o) {
 317         if (o == null) {
 318             for (int i = 0; i < size; i++)
 319                 if (elementData[i]==null)
 320                     return i;
 321         } else {
 322             for (int i = 0; i < size; i++)
 323                 if (o.equals(elementData[i]))
 324                     return i;
 325         }
 326         return -1;
 327     }
 328 
 329     /**
 330      * Returns the index of the last occurrence of the specified element
 331      * in this list, or -1 if this list does not contain the element.
 332      * More formally, returns the highest index {@code i} such that
 333      * {@code Objects.equals(o, get(i))},
 334      * or -1 if there is no such index.
 335      */
 336     public int lastIndexOf(Object o) {
 337         if (o == null) {
 338             for (int i = size-1; i >= 0; i--)
 339                 if (elementData[i]==null)
 340                     return i;
 341         } else {
 342             for (int i = size-1; i >= 0; i--)
 343                 if (o.equals(elementData[i]))
 344                     return i;
 345         }
 346         return -1;
 347     }
 348 
 349     /**
 350      * Returns a shallow copy of this {@code ArrayList} instance.  (The
 351      * elements themselves are not copied.)
 352      *
 353      * @return a clone of this {@code ArrayList} instance
 354      */
 355     public Object clone() {
 356         try {
 357             ArrayList<?> v = (ArrayList<?>) super.clone();
 358             v.elementData = Arrays.copyOf(elementData, size);
 359             v.modCount = 0;
 360             return v;
 361         } catch (CloneNotSupportedException e) {
 362             // this shouldn't happen, since we are Cloneable
 363             throw new InternalError(e);
 364         }
 365     }
 366 
 367     /**
 368      * Returns an array containing all of the elements in this list
 369      * in proper sequence (from first to last element).
 370      *
 371      * <p>The returned array will be "safe" in that no references to it are
 372      * maintained by this list.  (In other words, this method must allocate
 373      * a new array).  The caller is thus free to modify the returned array.
 374      *
 375      * <p>This method acts as bridge between array-based and collection-based
 376      * APIs.
 377      *
 378      * @return an array containing all of the elements in this list in
 379      *         proper sequence
 380      */
 381     public Object[] toArray() {
 382         return Arrays.copyOf(elementData, size);
 383     }
 384 
 385     /**
 386      * Returns an array containing all of the elements in this list in proper
 387      * sequence (from first to last element); the runtime type of the returned
 388      * array is that of the specified array.  If the list fits in the
 389      * specified array, it is returned therein.  Otherwise, a new array is
 390      * allocated with the runtime type of the specified array and the size of
 391      * this list.
 392      *
 393      * <p>If the list fits in the specified array with room to spare
 394      * (i.e., the array has more elements than the list), the element in
 395      * the array immediately following the end of the collection is set to
 396      * {@code null}.  (This is useful in determining the length of the
 397      * list <i>only</i> if the caller knows that the list does not contain
 398      * any null elements.)
 399      *
 400      * @param a the array into which the elements of the list are to
 401      *          be stored, if it is big enough; otherwise, a new array of the
 402      *          same runtime type is allocated for this purpose.
 403      * @return an array containing the elements of the list
 404      * @throws ArrayStoreException if the runtime type of the specified array
 405      *         is not a supertype of the runtime type of every element in
 406      *         this list
 407      * @throws NullPointerException if the specified array is null
 408      */
 409     @SuppressWarnings("unchecked")
 410     public <T> T[] toArray(T[] a) {
 411         if (a.length < size)
 412             // Make a new array of a's runtime type, but my contents:
 413             return (T[]) Arrays.copyOf(elementData, size, a.getClass());
 414         System.arraycopy(elementData, 0, a, 0, size);
 415         if (a.length > size)
 416             a[size] = null;
 417         return a;
 418     }
 419 
 420     // Positional Access Operations
 421 
 422     @SuppressWarnings("unchecked")
 423     E elementData(int index) {
 424         return (E) elementData[index];
 425     }
 426 
 427     @SuppressWarnings("unchecked")
 428     static <E> E elementAt(Object[] es, int index) {
 429         return (E) es[index];
 430     }
 431 
 432     /**
 433      * Returns the element at the specified position in this list.
 434      *
 435      * @param  index index of the element to return
 436      * @return the element at the specified position in this list
 437      * @throws IndexOutOfBoundsException {@inheritDoc}
 438      */
 439     public E get(int index) {
 440         Objects.checkIndex(index, size);
 441         return elementData(index);
 442     }
 443 
 444     /**
 445      * Replaces the element at the specified position in this list with
 446      * the specified element.
 447      *
 448      * @param index index of the element to replace
 449      * @param element element to be stored at the specified position
 450      * @return the element previously at the specified position
 451      * @throws IndexOutOfBoundsException {@inheritDoc}
 452      */
 453     public E set(int index, E element) {
 454         Objects.checkIndex(index, size);
 455         E oldValue = elementData(index);
 456         elementData[index] = element;
 457         return oldValue;
 458     }
 459 
 460     /**
 461      * This helper method split out from add(E) to keep method
 462      * bytecode size under 35 (the -XX:MaxInlineSize default value),
 463      * which helps when add(E) is called in a C1-compiled loop.
 464      */
 465     private void add(E e, Object[] elementData, int s) {
 466         if (s == elementData.length)
 467             elementData = grow();
 468         elementData[s] = e;
 469         size = s + 1;
 470     }
 471 
 472     /**
 473      * Appends the specified element to the end of this list.
 474      *
 475      * @param e element to be appended to this list
 476      * @return {@code true} (as specified by {@link Collection#add})
 477      */
 478     public boolean add(E e) {
 479         modCount++;
 480         add(e, elementData, size);
 481         return true;
 482     }
 483 
 484     /**
 485      * Inserts the specified element at the specified position in this
 486      * list. Shifts the element currently at that position (if any) and
 487      * any subsequent elements to the right (adds one to their indices).
 488      *
 489      * @param index index at which the specified element is to be inserted
 490      * @param element element to be inserted
 491      * @throws IndexOutOfBoundsException {@inheritDoc}
 492      */
 493     public void add(int index, E element) {
 494         rangeCheckForAdd(index);
 495         modCount++;
 496         final int s;
 497         Object[] elementData;
 498         if ((s = size) == (elementData = this.elementData).length)
 499             elementData = grow();
 500         System.arraycopy(elementData, index,
 501                          elementData, index + 1,
 502                          s - index);
 503         elementData[index] = element;
 504         size = s + 1;
 505     }
 506 
 507     /**
 508      * Removes the element at the specified position in this list.
 509      * Shifts any subsequent elements to the left (subtracts one from their
 510      * indices).
 511      *
 512      * @param index the index of the element to be removed
 513      * @return the element that was removed from the list
 514      * @throws IndexOutOfBoundsException {@inheritDoc}
 515      */
 516     public E remove(int index) {
 517         Objects.checkIndex(index, size);
 518         final Object[] es = elementData;
 519 
 520         @SuppressWarnings("unchecked") E oldValue = (E) es[index];
 521         fastRemove(es, index);
 522 
 523         return oldValue;
 524     }
 525 
 526     /**
 527      * Removes the first occurrence of the specified element from this list,
 528      * if it is present.  If the list does not contain the element, it is
 529      * unchanged.  More formally, removes the element with the lowest index
 530      * {@code i} such that
 531      * {@code Objects.equals(o, get(i))}
 532      * (if such an element exists).  Returns {@code true} if this list
 533      * contained the specified element (or equivalently, if this list
 534      * changed as a result of the call).
 535      *
 536      * @param o element to be removed from this list, if present
 537      * @return {@code true} if this list contained the specified element
 538      */
 539     public boolean remove(Object o) {
 540         final Object[] es = elementData;
 541         final int size = this.size;
 542         int i = 0;
 543         found: {
 544             if (o == null) {
 545                 for (; i < size; i++)
 546                     if (es[i] == null)
 547                         break found;
 548             } else {
 549                 for (; i < size; i++)
 550                     if (o.equals(es[i]))
 551                         break found;
 552             }
 553             return false;
 554         }
 555         fastRemove(es, i);
 556         return true;
 557     }
 558 
 559     /**
 560      * Private remove method that skips bounds checking and does not
 561      * return the value removed.
 562      */
 563     private void fastRemove(Object[] es, int i) {
 564         modCount++;
 565         final int newSize;
 566         if ((newSize = size - 1) > i)
 567             System.arraycopy(es, i + 1, es, i, newSize - i);
 568         es[size = newSize] = null;
 569     }
 570 
 571     /**
 572      * Removes all of the elements from this list.  The list will
 573      * be empty after this call returns.
 574      */
 575     public void clear() {
 576         modCount++;
 577         final Object[] es = elementData;
 578         for (int to = size, i = size = 0; i < to; i++)
 579             es[i] = null;
 580     }
 581 
 582     /**
 583      * Appends all of the elements in the specified collection to the end of
 584      * this list, in the order that they are returned by the
 585      * specified collection's Iterator.  The behavior of this operation is
 586      * undefined if the specified collection is modified while the operation
 587      * is in progress.  (This implies that the behavior of this call is
 588      * undefined if the specified collection is this list, and this
 589      * list is nonempty.)
 590      *
 591      * @param c collection containing elements to be added to this list
 592      * @return {@code true} if this list changed as a result of the call
 593      * @throws NullPointerException if the specified collection is null
 594      */
 595     public boolean addAll(Collection<? extends E> c) {
 596         Object[] a = c.toArray();
 597         modCount++;
 598         int numNew = a.length;
 599         if (numNew == 0)
 600             return false;
 601         Object[] elementData;
 602         final int s;
 603         if (numNew > (elementData = this.elementData).length - (s = size))
 604             elementData = grow(s + numNew);
 605         System.arraycopy(a, 0, elementData, s, numNew);
 606         size = s + numNew;
 607         return true;
 608     }
 609 
 610     /**
 611      * Inserts all of the elements in the specified collection into this
 612      * list, starting at the specified position.  Shifts the element
 613      * currently at that position (if any) and any subsequent elements to
 614      * the right (increases their indices).  The new elements will appear
 615      * in the list in the order that they are returned by the
 616      * specified collection's iterator.
 617      *
 618      * @param index index at which to insert the first element from the
 619      *              specified collection
 620      * @param c collection containing elements to be added to this list
 621      * @return {@code true} if this list changed as a result of the call
 622      * @throws IndexOutOfBoundsException {@inheritDoc}
 623      * @throws NullPointerException if the specified collection is null
 624      */
 625     public boolean addAll(int index, Collection<? extends E> c) {
 626         rangeCheckForAdd(index);
 627 
 628         Object[] a = c.toArray();
 629         modCount++;
 630         int numNew = a.length;
 631         if (numNew == 0)
 632             return false;
 633         Object[] elementData;
 634         final int s;
 635         if (numNew > (elementData = this.elementData).length - (s = size))
 636             elementData = grow(s + numNew);
 637 
 638         int numMoved = s - index;
 639         if (numMoved > 0)
 640             System.arraycopy(elementData, index,
 641                              elementData, index + numNew,
 642                              numMoved);
 643         System.arraycopy(a, 0, elementData, index, numNew);
 644         size = s + numNew;
 645         return true;
 646     }
 647 
 648     /**
 649      * Removes from this list all of the elements whose index is between
 650      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
 651      * Shifts any succeeding elements to the left (reduces their index).
 652      * This call shortens the list by {@code (toIndex - fromIndex)} elements.
 653      * (If {@code toIndex==fromIndex}, this operation has no effect.)
 654      *
 655      * @throws IndexOutOfBoundsException if {@code fromIndex} or
 656      *         {@code toIndex} is out of range
 657      *         ({@code fromIndex < 0 ||
 658      *          toIndex > size() ||
 659      *          toIndex < fromIndex})
 660      */
 661     protected void removeRange(int fromIndex, int toIndex) {
 662         if (fromIndex > toIndex) {
 663             throw new IndexOutOfBoundsException(
 664                     outOfBoundsMsg(fromIndex, toIndex));
 665         }
 666         modCount++;
 667         shiftTailOverGap(elementData, fromIndex, toIndex);
 668     }
 669 
 670     /** Erases the gap from lo to hi, by sliding down following elements. */
 671     private void shiftTailOverGap(Object[] es, int lo, int hi) {
 672         System.arraycopy(es, hi, es, lo, size - hi);
 673         for (int to = size, i = (size -= hi - lo); i < to; i++)
 674             es[i] = null;
 675     }
 676 
 677     /**
 678      * A version of rangeCheck used by add and addAll.
 679      */
 680     private void rangeCheckForAdd(int index) {
 681         if (index > size || index < 0)
 682             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 683     }
 684 
 685     /**
 686      * Constructs an IndexOutOfBoundsException detail message.
 687      * Of the many possible refactorings of the error handling code,
 688      * this "outlining" performs best with both server and client VMs.
 689      */
 690     private String outOfBoundsMsg(int index) {
 691         return "Index: "+index+", Size: "+size;
 692     }
 693 
 694     /**
 695      * A version used in checking (fromIndex > toIndex) condition
 696      */
 697     private static String outOfBoundsMsg(int fromIndex, int toIndex) {
 698         return "From Index: " + fromIndex + " > To Index: " + toIndex;
 699     }
 700 
 701     /**
 702      * Removes from this list all of its elements that are contained in the
 703      * specified collection.
 704      *
 705      * @param c collection containing elements to be removed from this list
 706      * @return {@code true} if this list changed as a result of the call
 707      * @throws ClassCastException if the class of an element of this list
 708      *         is incompatible with the specified collection
 709      * (<a href="Collection.html#optional-restrictions">optional</a>)
 710      * @throws NullPointerException if this list contains a null element and the
 711      *         specified collection does not permit null elements
 712      * (<a href="Collection.html#optional-restrictions">optional</a>),
 713      *         or if the specified collection is null
 714      * @see Collection#contains(Object)
 715      */
 716     public boolean removeAll(Collection<?> c) {
 717         return batchRemove(c, false, 0, size);
 718     }
 719 
 720     /**
 721      * Retains only the elements in this list that are contained in the
 722      * specified collection.  In other words, removes from this list all
 723      * of its elements that are not contained in the specified collection.
 724      *
 725      * @param c collection containing elements to be retained in this list
 726      * @return {@code true} if this list changed as a result of the call
 727      * @throws ClassCastException if the class of an element of this list
 728      *         is incompatible with the specified collection
 729      * (<a href="Collection.html#optional-restrictions">optional</a>)
 730      * @throws NullPointerException if this list contains a null element and the
 731      *         specified collection does not permit null elements
 732      * (<a href="Collection.html#optional-restrictions">optional</a>),
 733      *         or if the specified collection is null
 734      * @see Collection#contains(Object)
 735      */
 736     public boolean retainAll(Collection<?> c) {
 737         return batchRemove(c, true, 0, size);
 738     }
 739 
 740     boolean batchRemove(Collection<?> c, boolean complement,
 741                         final int from, final int end) {
 742         Objects.requireNonNull(c);
 743         final Object[] es = elementData;
 744         int r;
 745         // Optimize for initial run of survivors
 746         for (r = from;; r++) {
 747             if (r == end)
 748                 return false;
 749             if (c.contains(es[r]) != complement)
 750                 break;
 751         }
 752         int w = r++;
 753         try {
 754             for (Object e; r < end; r++)
 755                 if (c.contains(e = es[r]) == complement)
 756                     es[w++] = e;
 757         } catch (Throwable ex) {
 758             // Preserve behavioral compatibility with AbstractCollection,
 759             // even if c.contains() throws.
 760             System.arraycopy(es, r, es, w, end - r);
 761             w += end - r;
 762             throw ex;
 763         } finally {
 764             modCount += end - w;
 765             shiftTailOverGap(es, w, end);
 766         }
 767         return true;
 768     }
 769 
 770     /**
 771      * Saves the state of the {@code ArrayList} instance to a stream
 772      * (that is, serializes it).
 773      *
 774      * @param s the stream
 775      * @throws java.io.IOException if an I/O error occurs
 776      * @serialData The length of the array backing the {@code ArrayList}
 777      *             instance is emitted (int), followed by all of its elements
 778      *             (each an {@code Object}) in the proper order.
 779      */
 780     private void writeObject(java.io.ObjectOutputStream s)
 781         throws java.io.IOException {
 782         // Write out element count, and any hidden stuff
 783         int expectedModCount = modCount;
 784         s.defaultWriteObject();
 785 
 786         // Write out size as capacity for behavioral compatibility with clone()
 787         s.writeInt(size);
 788 
 789         // Write out all elements in the proper order.
 790         for (int i=0; i<size; i++) {
 791             s.writeObject(elementData[i]);
 792         }
 793 
 794         if (modCount != expectedModCount) {
 795             throw new ConcurrentModificationException();
 796         }
 797     }
 798 
 799     /**
 800      * Reconstitutes the {@code ArrayList} instance from a stream (that is,
 801      * deserializes it).
 802      * @param s the stream
 803      * @throws ClassNotFoundException if the class of a serialized object
 804      *         could not be found
 805      * @throws java.io.IOException if an I/O error occurs
 806      */
 807     private void readObject(java.io.ObjectInputStream s)
 808         throws java.io.IOException, ClassNotFoundException {
 809 
 810         // Read in size, and any hidden stuff
 811         s.defaultReadObject();
 812 
 813         // Read in capacity
 814         s.readInt(); // ignored
 815 
 816         if (size > 0) {
 817             // like clone(), allocate array based upon size not capacity
 818             SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);
 819             Object[] elements = new Object[size];
 820 
 821             // Read in all elements in the proper order.
 822             for (int i = 0; i < size; i++) {
 823                 elements[i] = s.readObject();
 824             }
 825 
 826             elementData = elements;
 827         } else if (size == 0) {
 828             elementData = EMPTY_ELEMENTDATA;
 829         } else {
 830             throw new java.io.InvalidObjectException("Invalid size: " + size);
 831         }
 832     }
 833 
 834     /**
 835      * Returns a list iterator over the elements in this list (in proper
 836      * sequence), starting at the specified position in the list.
 837      * The specified index indicates the first element that would be
 838      * returned by an initial call to {@link ListIterator#next next}.
 839      * An initial call to {@link ListIterator#previous previous} would
 840      * return the element with the specified index minus one.
 841      *
 842      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 843      *
 844      * @throws IndexOutOfBoundsException {@inheritDoc}
 845      */
 846     public ListIterator<E> listIterator(int index) {
 847         rangeCheckForAdd(index);
 848         return new ListItr(index);
 849     }
 850 
 851     /**
 852      * Returns a list iterator over the elements in this list (in proper
 853      * sequence).
 854      *
 855      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 856      *
 857      * @see #listIterator(int)
 858      */
 859     public ListIterator<E> listIterator() {
 860         return new ListItr(0);
 861     }
 862 
 863     /**
 864      * Returns an iterator over the elements in this list in proper sequence.
 865      *
 866      * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 867      *
 868      * @return an iterator over the elements in this list in proper sequence
 869      */
 870     public Iterator<E> iterator() {
 871         return new Itr();
 872     }
 873 
 874     /**
 875      * An optimized version of AbstractList.Itr
 876      */
 877     private class Itr implements Iterator<E> {
 878         int cursor;       // index of next element to return
 879         int lastRet = -1; // index of last element returned; -1 if no such
 880         int expectedModCount = modCount;
 881 
 882         // prevent creating a synthetic constructor
 883         Itr() {}
 884 
 885         public boolean hasNext() {
 886             return cursor != size;
 887         }
 888 
 889         @SuppressWarnings("unchecked")
 890         public E next() {
 891             checkForComodification();
 892             int i = cursor;
 893             if (i >= size)
 894                 throw new NoSuchElementException();
 895             Object[] elementData = ArrayList.this.elementData;
 896             if (i >= elementData.length)
 897                 throw new ConcurrentModificationException();
 898             cursor = i + 1;
 899             return (E) elementData[lastRet = i];
 900         }
 901 
 902         public void remove() {
 903             if (lastRet < 0)
 904                 throw new IllegalStateException();
 905             checkForComodification();
 906 
 907             try {
 908                 ArrayList.this.remove(lastRet);
 909                 cursor = lastRet;
 910                 lastRet = -1;
 911                 expectedModCount = modCount;
 912             } catch (IndexOutOfBoundsException ex) {
 913                 throw new ConcurrentModificationException();
 914             }
 915         }
 916 
 917         @Override
 918         public void forEachRemaining(Consumer<? super E> action) {
 919             Objects.requireNonNull(action);
 920             final int size = ArrayList.this.size;
 921             int i = cursor;
 922             if (i < size) {
 923                 final Object[] es = elementData;
 924                 if (i >= es.length)
 925                     throw new ConcurrentModificationException();
 926                 for (; i < size && modCount == expectedModCount; i++)
 927                     action.accept(elementAt(es, i));
 928                 // update once at end to reduce heap write traffic
 929                 cursor = i;
 930                 lastRet = i - 1;
 931                 checkForComodification();
 932             }
 933         }
 934 
 935         final void checkForComodification() {
 936             if (modCount != expectedModCount)
 937                 throw new ConcurrentModificationException();
 938         }
 939     }
 940 
 941     /**
 942      * An optimized version of AbstractList.ListItr
 943      */
 944     private class ListItr extends Itr implements ListIterator<E> {
 945         ListItr(int index) {
 946             super();
 947             cursor = index;
 948         }
 949 
 950         public boolean hasPrevious() {
 951             return cursor != 0;
 952         }
 953 
 954         public int nextIndex() {
 955             return cursor;
 956         }
 957 
 958         public int previousIndex() {
 959             return cursor - 1;
 960         }
 961 
 962         @SuppressWarnings("unchecked")
 963         public E previous() {
 964             checkForComodification();
 965             int i = cursor - 1;
 966             if (i < 0)
 967                 throw new NoSuchElementException();
 968             Object[] elementData = ArrayList.this.elementData;
 969             if (i >= elementData.length)
 970                 throw new ConcurrentModificationException();
 971             cursor = i;
 972             return (E) elementData[lastRet = i];
 973         }
 974 
 975         public void set(E e) {
 976             if (lastRet < 0)
 977                 throw new IllegalStateException();
 978             checkForComodification();
 979 
 980             try {
 981                 ArrayList.this.set(lastRet, e);
 982             } catch (IndexOutOfBoundsException ex) {
 983                 throw new ConcurrentModificationException();
 984             }
 985         }
 986 
 987         public void add(E e) {
 988             checkForComodification();
 989 
 990             try {
 991                 int i = cursor;
 992                 ArrayList.this.add(i, e);
 993                 cursor = i + 1;
 994                 lastRet = -1;
 995                 expectedModCount = modCount;
 996             } catch (IndexOutOfBoundsException ex) {
 997                 throw new ConcurrentModificationException();
 998             }
 999         }
1000     }
1001 
1002     /**
1003      * Returns a view of the portion of this list between the specified
1004      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.  (If
1005      * {@code fromIndex} and {@code toIndex} are equal, the returned list is
1006      * empty.)  The returned list is backed by this list, so non-structural
1007      * changes in the returned list are reflected in this list, and vice-versa.
1008      * The returned list supports all of the optional list operations.
1009      *
1010      * <p>This method eliminates the need for explicit range operations (of
1011      * the sort that commonly exist for arrays).  Any operation that expects
1012      * a list can be used as a range operation by passing a subList view
1013      * instead of a whole list.  For example, the following idiom
1014      * removes a range of elements from a list:
1015      * <pre>
1016      *      list.subList(from, to).clear();
1017      * </pre>
1018      * Similar idioms may be constructed for {@link #indexOf(Object)} and
1019      * {@link #lastIndexOf(Object)}, and all of the algorithms in the
1020      * {@link Collections} class can be applied to a subList.
1021      *
1022      * <p>The semantics of the list returned by this method become undefined if
1023      * the backing list (i.e., this list) is <i>structurally modified</i> in
1024      * any way other than via the returned list.  (Structural modifications are
1025      * those that change the size of this list, or otherwise perturb it in such
1026      * a fashion that iterations in progress may yield incorrect results.)
1027      *
1028      * @throws IndexOutOfBoundsException {@inheritDoc}
1029      * @throws IllegalArgumentException {@inheritDoc}
1030      */
1031     public List<E> subList(int fromIndex, int toIndex) {
1032         subListRangeCheck(fromIndex, toIndex, size);
1033         return new SubList<>(this, fromIndex, toIndex);
1034     }
1035 
1036     private static class SubList<E> extends AbstractList<E> implements RandomAccess {
1037         private final ArrayList<E> root;
1038         private final SubList<E> parent;
1039         private final int offset;
1040         private int size;
1041 
1042         /**
1043          * Constructs a sublist of an arbitrary ArrayList.
1044          */
1045         public SubList(ArrayList<E> root, int fromIndex, int toIndex) {
1046             this.root = root;
1047             this.parent = null;
1048             this.offset = fromIndex;
1049             this.size = toIndex - fromIndex;
1050             this.modCount = root.modCount;
1051         }
1052 
1053         /**
1054          * Constructs a sublist of another SubList.
1055          */
1056         private SubList(SubList<E> parent, int fromIndex, int toIndex) {
1057             this.root = parent.root;
1058             this.parent = parent;
1059             this.offset = parent.offset + fromIndex;
1060             this.size = toIndex - fromIndex;
1061             this.modCount = root.modCount;
1062         }
1063 
1064         public E set(int index, E element) {
1065             Objects.checkIndex(index, size);
1066             checkForComodification();
1067             E oldValue = root.elementData(offset + index);
1068             root.elementData[offset + index] = element;
1069             return oldValue;
1070         }
1071 
1072         public E get(int index) {
1073             Objects.checkIndex(index, size);
1074             checkForComodification();
1075             return root.elementData(offset + index);
1076         }
1077 
1078         public int size() {
1079             checkForComodification();
1080             return size;
1081         }
1082 
1083         public void add(int index, E element) {
1084             rangeCheckForAdd(index);
1085             checkForComodification();
1086             root.add(offset + index, element);
1087             updateSizeAndModCount(1);
1088         }
1089 
1090         public E remove(int index) {
1091             Objects.checkIndex(index, size);
1092             checkForComodification();
1093             E result = root.remove(offset + index);
1094             updateSizeAndModCount(-1);
1095             return result;
1096         }
1097 
1098         protected void removeRange(int fromIndex, int toIndex) {
1099             checkForComodification();
1100             root.removeRange(offset + fromIndex, offset + toIndex);
1101             updateSizeAndModCount(fromIndex - toIndex);
1102         }
1103 
1104         public boolean addAll(Collection<? extends E> c) {
1105             return addAll(this.size, c);
1106         }
1107 
1108         public boolean addAll(int index, Collection<? extends E> c) {
1109             rangeCheckForAdd(index);
1110             int cSize = c.size();
1111             if (cSize==0)
1112                 return false;
1113             checkForComodification();
1114             root.addAll(offset + index, c);
1115             updateSizeAndModCount(cSize);
1116             return true;
1117         }
1118 
1119         public boolean removeAll(Collection<?> c) {
1120             return batchRemove(c, false);
1121         }
1122 
1123         public boolean retainAll(Collection<?> c) {
1124             return batchRemove(c, true);
1125         }
1126 
1127         private boolean batchRemove(Collection<?> c, boolean complement) {
1128             checkForComodification();
1129             int oldSize = root.size;
1130             boolean modified =
1131                 root.batchRemove(c, complement, offset, offset + size);
1132             if (modified)
1133                 updateSizeAndModCount(root.size - oldSize);
1134             return modified;
1135         }
1136 
1137         public boolean removeIf(Predicate<? super E> filter) {
1138             checkForComodification();
1139             int oldSize = root.size;
1140             boolean modified = root.removeIf(filter, offset, offset + size);
1141             if (modified)
1142                 updateSizeAndModCount(root.size - oldSize);
1143             return modified;
1144         }
1145 
1146         public Object[] toArray() {
1147             checkForComodification();
1148             return Arrays.copyOfRange(root.elementData, offset, offset + size);
1149         }
1150 
1151         @SuppressWarnings("unchecked")
1152         public <T> T[] toArray(T[] a) {
1153             checkForComodification();
1154             if (a.length < size)
1155                 return (T[]) Arrays.copyOfRange(
1156                         root.elementData, offset, offset + size, a.getClass());
1157             System.arraycopy(root.elementData, offset, a, 0, size);
1158             if (a.length > size)
1159                 a[size] = null;
1160             return a;
1161         }
1162 
1163         public Iterator<E> iterator() {
1164             return listIterator();
1165         }
1166 
1167         public ListIterator<E> listIterator(int index) {
1168             checkForComodification();
1169             rangeCheckForAdd(index);
1170 
1171             return new ListIterator<E>() {
1172                 int cursor = index;
1173                 int lastRet = -1;
1174                 int expectedModCount = root.modCount;
1175 
1176                 public boolean hasNext() {
1177                     return cursor != SubList.this.size;
1178                 }
1179 
1180                 @SuppressWarnings("unchecked")
1181                 public E next() {
1182                     checkForComodification();
1183                     int i = cursor;
1184                     if (i >= SubList.this.size)
1185                         throw new NoSuchElementException();
1186                     Object[] elementData = root.elementData;
1187                     if (offset + i >= elementData.length)
1188                         throw new ConcurrentModificationException();
1189                     cursor = i + 1;
1190                     return (E) elementData[offset + (lastRet = i)];
1191                 }
1192 
1193                 public boolean hasPrevious() {
1194                     return cursor != 0;
1195                 }
1196 
1197                 @SuppressWarnings("unchecked")
1198                 public E previous() {
1199                     checkForComodification();
1200                     int i = cursor - 1;
1201                     if (i < 0)
1202                         throw new NoSuchElementException();
1203                     Object[] elementData = root.elementData;
1204                     if (offset + i >= elementData.length)
1205                         throw new ConcurrentModificationException();
1206                     cursor = i;
1207                     return (E) elementData[offset + (lastRet = i)];
1208                 }
1209 
1210                 public void forEachRemaining(Consumer<? super E> action) {
1211                     Objects.requireNonNull(action);
1212                     final int size = SubList.this.size;
1213                     int i = cursor;
1214                     if (i < size) {
1215                         final Object[] es = root.elementData;
1216                         if (offset + i >= es.length)
1217                             throw new ConcurrentModificationException();
1218                         for (; i < size && modCount == expectedModCount; i++)
1219                             action.accept(elementAt(es, offset + i));
1220                         // update once at end to reduce heap write traffic
1221                         cursor = i;
1222                         lastRet = i - 1;
1223                         checkForComodification();
1224                     }
1225                 }
1226 
1227                 public int nextIndex() {
1228                     return cursor;
1229                 }
1230 
1231                 public int previousIndex() {
1232                     return cursor - 1;
1233                 }
1234 
1235                 public void remove() {
1236                     if (lastRet < 0)
1237                         throw new IllegalStateException();
1238                     checkForComodification();
1239 
1240                     try {
1241                         SubList.this.remove(lastRet);
1242                         cursor = lastRet;
1243                         lastRet = -1;
1244                         expectedModCount = root.modCount;
1245                     } catch (IndexOutOfBoundsException ex) {
1246                         throw new ConcurrentModificationException();
1247                     }
1248                 }
1249 
1250                 public void set(E e) {
1251                     if (lastRet < 0)
1252                         throw new IllegalStateException();
1253                     checkForComodification();
1254 
1255                     try {
1256                         root.set(offset + lastRet, e);
1257                     } catch (IndexOutOfBoundsException ex) {
1258                         throw new ConcurrentModificationException();
1259                     }
1260                 }
1261 
1262                 public void add(E e) {
1263                     checkForComodification();
1264 
1265                     try {
1266                         int i = cursor;
1267                         SubList.this.add(i, e);
1268                         cursor = i + 1;
1269                         lastRet = -1;
1270                         expectedModCount = root.modCount;
1271                     } catch (IndexOutOfBoundsException ex) {
1272                         throw new ConcurrentModificationException();
1273                     }
1274                 }
1275 
1276                 final void checkForComodification() {
1277                     if (root.modCount != expectedModCount)
1278                         throw new ConcurrentModificationException();
1279                 }
1280             };
1281         }
1282 
1283         public List<E> subList(int fromIndex, int toIndex) {
1284             subListRangeCheck(fromIndex, toIndex, size);
1285             return new SubList<>(this, fromIndex, toIndex);
1286         }
1287 
1288         private void rangeCheckForAdd(int index) {
1289             if (index < 0 || index > this.size)
1290                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1291         }
1292 
1293         private String outOfBoundsMsg(int index) {
1294             return "Index: "+index+", Size: "+this.size;
1295         }
1296 
1297         private void checkForComodification() {
1298             if (root.modCount != modCount)
1299                 throw new ConcurrentModificationException();
1300         }
1301 
1302         private void updateSizeAndModCount(int sizeChange) {
1303             SubList<E> slist = this;
1304             do {
1305                 slist.size += sizeChange;
1306                 slist.modCount = root.modCount;
1307                 slist = slist.parent;
1308             } while (slist != null);
1309         }
1310 
1311         public Spliterator<E> spliterator() {
1312             checkForComodification();
1313 
1314             // ArrayListSpliterator not used here due to late-binding
1315             return new Spliterator<E>() {
1316                 private int index = offset; // current index, modified on advance/split
1317                 private int fence = -1; // -1 until used; then one past last index
1318                 private int expectedModCount; // initialized when fence set
1319 
1320                 private int getFence() { // initialize fence to size on first use
1321                     int hi; // (a specialized variant appears in method forEach)
1322                     if ((hi = fence) < 0) {
1323                         expectedModCount = modCount;
1324                         hi = fence = offset + size;
1325                     }
1326                     return hi;
1327                 }
1328 
1329                 public ArrayList<E>.ArrayListSpliterator trySplit() {
1330                     int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1331                     // ArrayListSpliterator can be used here as the source is already bound
1332                     return (lo >= mid) ? null : // divide range in half unless too small
1333                         root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
1334                 }
1335 
1336                 public boolean tryAdvance(Consumer<? super E> action) {
1337                     Objects.requireNonNull(action);
1338                     int hi = getFence(), i = index;
1339                     if (i < hi) {
1340                         index = i + 1;
1341                         @SuppressWarnings("unchecked") E e = (E)root.elementData[i];
1342                         action.accept(e);
1343                         if (root.modCount != expectedModCount)
1344                             throw new ConcurrentModificationException();
1345                         return true;
1346                     }
1347                     return false;
1348                 }
1349 
1350                 public void forEachRemaining(Consumer<? super E> action) {
1351                     Objects.requireNonNull(action);
1352                     int i, hi, mc; // hoist accesses and checks from loop
1353                     ArrayList<E> lst = root;
1354                     Object[] a;
1355                     if ((a = lst.elementData) != null) {
1356                         if ((hi = fence) < 0) {
1357                             mc = modCount;
1358                             hi = offset + size;
1359                         }
1360                         else
1361                             mc = expectedModCount;
1362                         if ((i = index) >= 0 && (index = hi) <= a.length) {
1363                             for (; i < hi; ++i) {
1364                                 @SuppressWarnings("unchecked") E e = (E) a[i];
1365                                 action.accept(e);
1366                             }
1367                             if (lst.modCount == mc)
1368                                 return;
1369                         }
1370                     }
1371                     throw new ConcurrentModificationException();
1372                 }
1373 
1374                 public long estimateSize() {
1375                     return getFence() - index;
1376                 }
1377 
1378                 public int characteristics() {
1379                     return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1380                 }
1381             };
1382         }
1383     }
1384 
1385     /**
1386      * @throws NullPointerException {@inheritDoc}
1387      */
1388     @Override
1389     public void forEach(Consumer<? super E> action) {
1390         Objects.requireNonNull(action);
1391         final int expectedModCount = modCount;
1392         final Object[] es = elementData;
1393         final int size = this.size;
1394         for (int i = 0; modCount == expectedModCount && i < size; i++)
1395             action.accept(elementAt(es, i));
1396         if (modCount != expectedModCount)
1397             throw new ConcurrentModificationException();
1398     }
1399 
1400     /**
1401      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1402      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1403      * list.
1404      *
1405      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1406      * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1407      * Overriding implementations should document the reporting of additional
1408      * characteristic values.
1409      *
1410      * @return a {@code Spliterator} over the elements in this list
1411      * @since 1.8
1412      */
1413     @Override
1414     public Spliterator<E> spliterator() {
1415         return new ArrayListSpliterator(0, -1, 0);
1416     }
1417 
1418     /** Index-based split-by-two, lazily initialized Spliterator */
1419     final class ArrayListSpliterator implements Spliterator<E> {
1420 
1421         /*
1422          * If ArrayLists were immutable, or structurally immutable (no
1423          * adds, removes, etc), we could implement their spliterators
1424          * with Arrays.spliterator. Instead we detect as much
1425          * interference during traversal as practical without
1426          * sacrificing much performance. We rely primarily on
1427          * modCounts. These are not guaranteed to detect concurrency
1428          * violations, and are sometimes overly conservative about
1429          * within-thread interference, but detect enough problems to
1430          * be worthwhile in practice. To carry this out, we (1) lazily
1431          * initialize fence and expectedModCount until the latest
1432          * point that we need to commit to the state we are checking
1433          * against; thus improving precision.  (This doesn't apply to
1434          * SubLists, that create spliterators with current non-lazy
1435          * values).  (2) We perform only a single
1436          * ConcurrentModificationException check at the end of forEach
1437          * (the most performance-sensitive method). When using forEach
1438          * (as opposed to iterators), we can normally only detect
1439          * interference after actions, not before. Further
1440          * CME-triggering checks apply to all other possible
1441          * violations of assumptions for example null or too-small
1442          * elementData array given its size(), that could only have
1443          * occurred due to interference.  This allows the inner loop
1444          * of forEach to run without any further checks, and
1445          * simplifies lambda-resolution. While this does entail a
1446          * number of checks, note that in the common case of
1447          * list.stream().forEach(a), no checks or other computation
1448          * occur anywhere other than inside forEach itself.  The other
1449          * less-often-used methods cannot take advantage of most of
1450          * these streamlinings.
1451          */
1452 
1453         private int index; // current index, modified on advance/split
1454         private int fence; // -1 until used; then one past last index
1455         private int expectedModCount; // initialized when fence set
1456 
1457         /** Creates new spliterator covering the given range. */
1458         ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1459             this.index = origin;
1460             this.fence = fence;
1461             this.expectedModCount = expectedModCount;
1462         }
1463 
1464         private int getFence() { // initialize fence to size on first use
1465             int hi; // (a specialized variant appears in method forEach)
1466             if ((hi = fence) < 0) {
1467                 expectedModCount = modCount;
1468                 hi = fence = size;
1469             }
1470             return hi;
1471         }
1472 
1473         public ArrayListSpliterator trySplit() {
1474             int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1475             return (lo >= mid) ? null : // divide range in half unless too small
1476                 new ArrayListSpliterator(lo, index = mid, expectedModCount);
1477         }
1478 
1479         public boolean tryAdvance(Consumer<? super E> action) {
1480             if (action == null)
1481                 throw new NullPointerException();
1482             int hi = getFence(), i = index;
1483             if (i < hi) {
1484                 index = i + 1;
1485                 @SuppressWarnings("unchecked") E e = (E)elementData[i];
1486                 action.accept(e);
1487                 if (modCount != expectedModCount)
1488                     throw new ConcurrentModificationException();
1489                 return true;
1490             }
1491             return false;
1492         }
1493 
1494         public void forEachRemaining(Consumer<? super E> action) {
1495             int i, hi, mc; // hoist accesses and checks from loop
1496             Object[] a;
1497             if (action == null)
1498                 throw new NullPointerException();
1499             if ((a = elementData) != null) {
1500                 if ((hi = fence) < 0) {
1501                     mc = modCount;
1502                     hi = size;
1503                 }
1504                 else
1505                     mc = expectedModCount;
1506                 if ((i = index) >= 0 && (index = hi) <= a.length) {
1507                     for (; i < hi; ++i) {
1508                         @SuppressWarnings("unchecked") E e = (E) a[i];
1509                         action.accept(e);
1510                     }
1511                     if (modCount == mc)
1512                         return;
1513                 }
1514             }
1515             throw new ConcurrentModificationException();
1516         }
1517 
1518         public long estimateSize() {
1519             return getFence() - index;
1520         }
1521 
1522         public int characteristics() {
1523             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1524         }
1525     }
1526 
1527     // A tiny bit set implementation
1528 
1529     private static long[] nBits(int n) {
1530         return new long[((n - 1) >> 6) + 1];
1531     }
1532     private static void setBit(long[] bits, int i) {
1533         bits[i >> 6] |= 1L << i;
1534     }
1535     private static boolean isClear(long[] bits, int i) {
1536         return (bits[i >> 6] & (1L << i)) == 0;
1537     }
1538 
1539     /**
1540      * @throws NullPointerException {@inheritDoc}
1541      */
1542     @Override
1543     public boolean removeIf(Predicate<? super E> filter) {
1544         return removeIf(filter, 0, size);
1545     }
1546 
1547     /**
1548      * Removes all elements satisfying the given predicate, from index
1549      * i (inclusive) to index end (exclusive).
1550      */
1551     boolean removeIf(Predicate<? super E> filter, int i, final int end) {
1552         Objects.requireNonNull(filter);
1553         int expectedModCount = modCount;
1554         final Object[] es = elementData;
1555         // Optimize for initial run of survivors
1556         for (; i < end && !filter.test(elementAt(es, i)); i++)
1557             ;
1558         // Tolerate predicates that reentrantly access the collection for
1559         // read (but writers still get CME), so traverse once to find
1560         // elements to delete, a second pass to physically expunge.
1561         if (i < end) {
1562             final int beg = i;
1563             final long[] deathRow = nBits(end - beg);
1564             deathRow[0] = 1L;   // set bit 0
1565             for (i = beg + 1; i < end; i++)
1566                 if (filter.test(elementAt(es, i)))
1567                     setBit(deathRow, i - beg);
1568             if (modCount != expectedModCount)
1569                 throw new ConcurrentModificationException();
1570             modCount++;
1571             int w = beg;
1572             for (i = beg; i < end; i++)
1573                 if (isClear(deathRow, i - beg))
1574                     es[w++] = es[i];
1575             shiftTailOverGap(es, w, end);
1576             return true;
1577         } else {
1578             if (modCount != expectedModCount)
1579                 throw new ConcurrentModificationException();
1580             return false;
1581         }
1582     }
1583 
1584     @Override
1585     public void replaceAll(UnaryOperator<E> operator) {
1586         Objects.requireNonNull(operator);
1587         final int expectedModCount = modCount;
1588         final Object[] es = elementData;
1589         final int size = this.size;
1590         for (int i = 0; modCount == expectedModCount && i < size; i++)
1591             es[i] = operator.apply(elementAt(es, i));
1592         if (modCount != expectedModCount)
1593             throw new ConcurrentModificationException();
1594         modCount++;
1595     }
1596 
1597     @Override
1598     @SuppressWarnings("unchecked")
1599     public void sort(Comparator<? super E> c) {
1600         final int expectedModCount = modCount;
1601         Arrays.sort((E[]) elementData, 0, size, c);
1602         if (modCount != expectedModCount)
1603             throw new ConcurrentModificationException();
1604         modCount++;
1605     }
1606 
1607     void checkInvariants() {
1608         // assert size >= 0;
1609         // assert size == elementData.length || elementData[size] == null;
1610     }
1611 }