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