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