1 /*
   2  * Copyright (c) 1997, 2012, 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.Block;
  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      * The array buffer into which the elements of the ArrayList are stored.
 113      * The capacity of the ArrayList is the length of this array buffer.
 114      */
 115     private transient Object[] elementData;
 116 
 117     /**
 118      * The size of the ArrayList (the number of elements it contains).
 119      *
 120      * @serial
 121      */
 122     private int size;
 123 
 124     /**
 125      * Constructs an empty list with the specified initial capacity.
 126      *
 127      * @param  initialCapacity  the initial capacity of the list
 128      * @throws IllegalArgumentException if the specified initial capacity
 129      *         is negative
 130      */
 131     public ArrayList(int initialCapacity) {
 132         super();
 133         if (initialCapacity < 0)
 134             throw new IllegalArgumentException("Illegal Capacity: "+
 135                                                initialCapacity);
 136         this.elementData = new Object[initialCapacity];
 137     }
 138 
 139     /**
 140      * Constructs an empty list with an initial capacity of ten.
 141      */
 142     public ArrayList() {
 143         this(10);
 144     }
 145 
 146     /**
 147      * Constructs a list containing the elements of the specified
 148      * collection, in the order they are returned by the collection's
 149      * iterator.
 150      *
 151      * @param c the collection whose elements are to be placed into this list
 152      * @throws NullPointerException if the specified collection is null
 153      */
 154     public ArrayList(Collection<? extends E> c) {
 155         elementData = c.toArray();
 156         size = elementData.length;
 157         // c.toArray might (incorrectly) not return Object[] (see 6260652)
 158         if (elementData.getClass() != Object[].class)
 159             elementData = Arrays.copyOf(elementData, size, Object[].class);
 160     }
 161 
 162     /**
 163      * Trims the capacity of this <tt>ArrayList</tt> instance to be the
 164      * list's current size.  An application can use this operation to minimize
 165      * the storage of an <tt>ArrayList</tt> instance.
 166      */
 167     public void trimToSize() {
 168         modCount++;
 169         int oldCapacity = elementData.length;
 170         if (size < oldCapacity) {
 171             elementData = Arrays.copyOf(elementData, size);
 172         }
 173     }
 174 
 175     /**
 176      * Increases the capacity of this <tt>ArrayList</tt> instance, if
 177      * necessary, to ensure that it can hold at least the number of elements
 178      * specified by the minimum capacity argument.
 179      *
 180      * @param   minCapacity   the desired minimum capacity
 181      */
 182     public void ensureCapacity(int minCapacity) {
 183         if (minCapacity > 0)
 184             ensureCapacityInternal(minCapacity);
 185     }
 186 
 187     private void ensureCapacityInternal(int minCapacity) {
 188         modCount++;
 189         // overflow-conscious code
 190         if (minCapacity - elementData.length > 0)
 191             grow(minCapacity);
 192     }
 193 
 194     /**
 195      * The maximum size of array to allocate.
 196      * Some VMs reserve some header words in an array.
 197      * Attempts to allocate larger arrays may result in
 198      * OutOfMemoryError: Requested array size exceeds VM limit
 199      */
 200     private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
 201 
 202     /**
 203      * Increases the capacity to ensure that it can hold at least the
 204      * number of elements specified by the minimum capacity argument.
 205      *
 206      * @param minCapacity the desired minimum capacity
 207      */
 208     private void grow(int minCapacity) {
 209         // overflow-conscious code
 210         int oldCapacity = elementData.length;
 211         int newCapacity = oldCapacity + (oldCapacity >> 1);
 212         if (newCapacity - minCapacity < 0)
 213             newCapacity = minCapacity;
 214         if (newCapacity - MAX_ARRAY_SIZE > 0)
 215             newCapacity = hugeCapacity(minCapacity);
 216         // minCapacity is usually close to size, so this is a win:
 217         elementData = Arrays.copyOf(elementData, newCapacity);
 218     }
 219 
 220     private static int hugeCapacity(int minCapacity) {
 221         if (minCapacity < 0) // overflow
 222             throw new OutOfMemoryError();
 223         return (minCapacity > MAX_ARRAY_SIZE) ?
 224             Integer.MAX_VALUE :
 225             MAX_ARRAY_SIZE;
 226     }
 227 
 228     /**
 229      * Returns the number of elements in this list.
 230      *
 231      * @return the number of elements in this list
 232      */
 233     public int size() {
 234         return size;
 235     }
 236 
 237     /**
 238      * Returns <tt>true</tt> if this list contains no elements.
 239      *
 240      * @return <tt>true</tt> if this list contains no elements
 241      */
 242     public boolean isEmpty() {
 243         return size == 0;
 244     }
 245 
 246     /**
 247      * Returns <tt>true</tt> if this list contains the specified element.
 248      * More formally, returns <tt>true</tt> if and only if this list contains
 249      * at least one element <tt>e</tt> such that
 250      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
 251      *
 252      * @param o element whose presence in this list is to be tested
 253      * @return <tt>true</tt> if this list contains the specified element
 254      */
 255     public boolean contains(Object o) {
 256         return indexOf(o) >= 0;
 257     }
 258 
 259     /**
 260      * Returns the index of the first occurrence of the specified element
 261      * in this list, or -1 if this list does not contain the element.
 262      * More formally, returns the lowest index <tt>i</tt> such that
 263      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
 264      * or -1 if there is no such index.
 265      */
 266     public int indexOf(Object o) {
 267         if (o == null) {
 268             for (int i = 0; i < size; i++)
 269                 if (elementData[i]==null)
 270                     return i;
 271         } else {
 272             for (int i = 0; i < size; i++)
 273                 if (o.equals(elementData[i]))
 274                     return i;
 275         }
 276         return -1;
 277     }
 278 
 279     /**
 280      * Returns the index of the last occurrence of the specified element
 281      * in this list, or -1 if this list does not contain the element.
 282      * More formally, returns the highest index <tt>i</tt> such that
 283      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
 284      * or -1 if there is no such index.
 285      */
 286     public int lastIndexOf(Object o) {
 287         if (o == null) {
 288             for (int i = size-1; i >= 0; i--)
 289                 if (elementData[i]==null)
 290                     return i;
 291         } else {
 292             for (int i = size-1; i >= 0; i--)
 293                 if (o.equals(elementData[i]))
 294                     return i;
 295         }
 296         return -1;
 297     }
 298 
 299     /**
 300      * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
 301      * elements themselves are not copied.)
 302      *
 303      * @return a clone of this <tt>ArrayList</tt> instance
 304      */
 305     public Object clone() {
 306         try {
 307             ArrayList<?> v = (ArrayList<?>) super.clone();
 308             v.elementData = Arrays.copyOf(elementData, size);
 309             v.modCount = 0;
 310             return v;
 311         } catch (CloneNotSupportedException e) {
 312             // this shouldn't happen, since we are Cloneable
 313             throw new InternalError(e);
 314         }
 315     }
 316 
 317     /**
 318      * Returns an array containing all of the elements in this list
 319      * in proper sequence (from first to last element).
 320      *
 321      * <p>The returned array will be "safe" in that no references to it are
 322      * maintained by this list.  (In other words, this method must allocate
 323      * a new array).  The caller is thus free to modify the returned array.
 324      *
 325      * <p>This method acts as bridge between array-based and collection-based
 326      * APIs.
 327      *
 328      * @return an array containing all of the elements in this list in
 329      *         proper sequence
 330      */
 331     public Object[] toArray() {
 332         return Arrays.copyOf(elementData, size);
 333     }
 334 
 335     /**
 336      * Returns an array containing all of the elements in this list in proper
 337      * sequence (from first to last element); the runtime type of the returned
 338      * array is that of the specified array.  If the list fits in the
 339      * specified array, it is returned therein.  Otherwise, a new array is
 340      * allocated with the runtime type of the specified array and the size of
 341      * this list.
 342      *
 343      * <p>If the list fits in the specified array with room to spare
 344      * (i.e., the array has more elements than the list), the element in
 345      * the array immediately following the end of the collection is set to
 346      * <tt>null</tt>.  (This is useful in determining the length of the
 347      * list <i>only</i> if the caller knows that the list does not contain
 348      * any null elements.)
 349      *
 350      * @param a the array into which the elements of the list are to
 351      *          be stored, if it is big enough; otherwise, a new array of the
 352      *          same runtime type is allocated for this purpose.
 353      * @return an array containing the elements of the list
 354      * @throws ArrayStoreException if the runtime type of the specified array
 355      *         is not a supertype of the runtime type of every element in
 356      *         this list
 357      * @throws NullPointerException if the specified array is null
 358      */
 359     @SuppressWarnings("unchecked")
 360     public <T> T[] toArray(T[] a) {
 361         if (a.length < size)
 362             // Make a new array of a's runtime type, but my contents:
 363             return (T[]) Arrays.copyOf(elementData, size, a.getClass());
 364         System.arraycopy(elementData, 0, a, 0, size);
 365         if (a.length > size)
 366             a[size] = null;
 367         return a;
 368     }
 369 
 370     // Positional Access Operations
 371 
 372     @SuppressWarnings("unchecked")
 373     E elementData(int index) {
 374         return (E) elementData[index];
 375     }
 376 
 377     /**
 378      * Returns the element at the specified position in this list.
 379      *
 380      * @param  index index of the element to return
 381      * @return the element at the specified position in this list
 382      * @throws IndexOutOfBoundsException {@inheritDoc}
 383      */
 384     public E get(int index) {
 385         rangeCheck(index);
 386 
 387         return elementData(index);
 388     }
 389 
 390     /**
 391      * Replaces the element at the specified position in this list with
 392      * the specified element.
 393      *
 394      * @param index index of the element to replace
 395      * @param element element to be stored at the specified position
 396      * @return the element previously at the specified position
 397      * @throws IndexOutOfBoundsException {@inheritDoc}
 398      */
 399     public E set(int index, E element) {
 400         rangeCheck(index);
 401 
 402         E oldValue = elementData(index);
 403         elementData[index] = element;
 404         return oldValue;
 405     }
 406 
 407     /**
 408      * Appends the specified element to the end of this list.
 409      *
 410      * @param e element to be appended to this list
 411      * @return <tt>true</tt> (as specified by {@link Collection#add})
 412      */
 413     public boolean add(E e) {
 414         ensureCapacityInternal(size + 1);  // Increments modCount!!
 415         elementData[size++] = e;
 416         return true;
 417     }
 418 
 419     /**
 420      * Inserts the specified element at the specified position in this
 421      * list. Shifts the element currently at that position (if any) and
 422      * any subsequent elements to the right (adds one to their indices).
 423      *
 424      * @param index index at which the specified element is to be inserted
 425      * @param element element to be inserted
 426      * @throws IndexOutOfBoundsException {@inheritDoc}
 427      */
 428     public void add(int index, E element) {
 429         rangeCheckForAdd(index);
 430 
 431         ensureCapacityInternal(size + 1);  // Increments modCount!!
 432         System.arraycopy(elementData, index, elementData, index + 1,
 433                          size - index);
 434         elementData[index] = element;
 435         size++;
 436     }
 437 
 438     /**
 439      * Removes the element at the specified position in this list.
 440      * Shifts any subsequent elements to the left (subtracts one from their
 441      * indices).
 442      *
 443      * @param index the index of the element to be removed
 444      * @return the element that was removed from the list
 445      * @throws IndexOutOfBoundsException {@inheritDoc}
 446      */
 447     public E remove(int index) {
 448         rangeCheck(index);
 449 
 450         modCount++;
 451         E oldValue = elementData(index);
 452 
 453         int numMoved = size - index - 1;
 454         if (numMoved > 0)
 455             System.arraycopy(elementData, index+1, elementData, index,
 456                              numMoved);
 457         elementData[--size] = null; // Let gc do its work
 458 
 459         return oldValue;
 460     }
 461 
 462     /**
 463      * Removes the first occurrence of the specified element from this list,
 464      * if it is present.  If the list does not contain the element, it is
 465      * unchanged.  More formally, removes the element with the lowest index
 466      * <tt>i</tt> such that
 467      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
 468      * (if such an element exists).  Returns <tt>true</tt> if this list
 469      * contained the specified element (or equivalently, if this list
 470      * changed as a result of the call).
 471      *
 472      * @param o element to be removed from this list, if present
 473      * @return <tt>true</tt> if this list contained the specified element
 474      */
 475     public boolean remove(Object o) {
 476         if (o == null) {
 477             for (int index = 0; index < size; index++)
 478                 if (elementData[index] == null) {
 479                     fastRemove(index);
 480                     return true;
 481                 }
 482         } else {
 483             for (int index = 0; index < size; index++)
 484                 if (o.equals(elementData[index])) {
 485                     fastRemove(index);
 486                     return true;
 487                 }
 488         }
 489         return false;
 490     }
 491 
 492     /*
 493      * Private remove method that skips bounds checking and does not
 494      * return the value removed.
 495      */
 496     private void fastRemove(int index) {
 497         modCount++;
 498         int numMoved = size - index - 1;
 499         if (numMoved > 0)
 500             System.arraycopy(elementData, index+1, elementData, index,
 501                              numMoved);
 502         elementData[--size] = null; // Let gc do its work
 503     }
 504 
 505     /**
 506      * Removes all of the elements from this list.  The list will
 507      * be empty after this call returns.
 508      */
 509     public void clear() {
 510         modCount++;
 511 
 512         // Let gc do its work
 513         for (int i = 0; i < size; i++)
 514             elementData[i] = null;
 515 
 516         size = 0;
 517     }
 518 
 519     /**
 520      * Appends all of the elements in the specified collection to the end of
 521      * this list, in the order that they are returned by the
 522      * specified collection's Iterator.  The behavior of this operation is
 523      * undefined if the specified collection is modified while the operation
 524      * is in progress.  (This implies that the behavior of this call is
 525      * undefined if the specified collection is this list, and this
 526      * list is nonempty.)
 527      *
 528      * @param c collection containing elements to be added to this list
 529      * @return <tt>true</tt> if this list changed as a result of the call
 530      * @throws NullPointerException if the specified collection is null
 531      */
 532     public boolean addAll(Collection<? extends E> c) {
 533         Object[] a = c.toArray();
 534         int numNew = a.length;
 535         ensureCapacityInternal(size + numNew);  // Increments modCount
 536         System.arraycopy(a, 0, elementData, size, numNew);
 537         size += numNew;
 538         return numNew != 0;
 539     }
 540 
 541     /**
 542      * Inserts all of the elements in the specified collection into this
 543      * list, starting at the specified position.  Shifts the element
 544      * currently at that position (if any) and any subsequent elements to
 545      * the right (increases their indices).  The new elements will appear
 546      * in the list in the order that they are returned by the
 547      * specified collection's iterator.
 548      *
 549      * @param index index at which to insert the first element from the
 550      *              specified collection
 551      * @param c collection containing elements to be added to this list
 552      * @return <tt>true</tt> if this list changed as a result of the call
 553      * @throws IndexOutOfBoundsException {@inheritDoc}
 554      * @throws NullPointerException if the specified collection is null
 555      */
 556     public boolean addAll(int index, Collection<? extends E> c) {
 557         rangeCheckForAdd(index);
 558 
 559         Object[] a = c.toArray();
 560         int numNew = a.length;
 561         ensureCapacityInternal(size + numNew);  // Increments modCount
 562 
 563         int numMoved = size - index;
 564         if (numMoved > 0)
 565             System.arraycopy(elementData, index, elementData, index + numNew,
 566                              numMoved);
 567 
 568         System.arraycopy(a, 0, elementData, index, numNew);
 569         size += numNew;
 570         return numNew != 0;
 571     }
 572 
 573     /**
 574      * Removes from this list all of the elements whose index is between
 575      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
 576      * Shifts any succeeding elements to the left (reduces their index).
 577      * This call shortens the list by {@code (toIndex - fromIndex)} elements.
 578      * (If {@code toIndex==fromIndex}, this operation has no effect.)
 579      *
 580      * @throws IndexOutOfBoundsException if {@code fromIndex} or
 581      *         {@code toIndex} is out of range
 582      *         ({@code fromIndex < 0 ||
 583      *          fromIndex >= size() ||
 584      *          toIndex > size() ||
 585      *          toIndex < fromIndex})
 586      */
 587     protected void removeRange(int fromIndex, int toIndex) {
 588         modCount++;
 589         int numMoved = size - toIndex;
 590         System.arraycopy(elementData, toIndex, elementData, fromIndex,
 591                          numMoved);
 592 
 593         // Let gc do its work
 594         int newSize = size - (toIndex-fromIndex);
 595         while (size != newSize)
 596             elementData[--size] = null;
 597     }
 598 
 599     /**
 600      * Checks if the given index is in range.  If not, throws an appropriate
 601      * runtime exception.  This method does *not* check if the index is
 602      * negative: It is always used immediately prior to an array access,
 603      * which throws an ArrayIndexOutOfBoundsException if index is negative.
 604      */
 605     private void rangeCheck(int index) {
 606         if (index >= size)
 607             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 608     }
 609 
 610     /**
 611      * A version of rangeCheck used by add and addAll.
 612      */
 613     private void rangeCheckForAdd(int index) {
 614         if (index > size || index < 0)
 615             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
 616     }
 617 
 618     /**
 619      * Constructs an IndexOutOfBoundsException detail message.
 620      * Of the many possible refactorings of the error handling code,
 621      * this "outlining" performs best with both server and client VMs.
 622      */
 623     private String outOfBoundsMsg(int index) {
 624         return "Index: "+index+", Size: "+size;
 625     }
 626 
 627     /**
 628      * Removes from this list all of its elements that are contained in the
 629      * specified collection.
 630      *
 631      * @param c collection containing elements to be removed from this list
 632      * @return {@code true} if this list changed as a result of the call
 633      * @throws ClassCastException if the class of an element of this list
 634      *         is incompatible with the specified collection
 635      * (<a href="Collection.html#optional-restrictions">optional</a>)
 636      * @throws NullPointerException if this list contains a null element and the
 637      *         specified collection does not permit null elements
 638      * (<a href="Collection.html#optional-restrictions">optional</a>),
 639      *         or if the specified collection is null
 640      * @see Collection#contains(Object)
 641      */
 642     public boolean removeAll(Collection<?> c) {
 643         return batchRemove(c, false);
 644     }
 645 
 646     /**
 647      * Retains only the elements in this list that are contained in the
 648      * specified collection.  In other words, removes from this list all
 649      * of its elements that are not contained in the specified collection.
 650      *
 651      * @param c collection containing elements to be retained in this list
 652      * @return {@code true} if this list changed as a result of the call
 653      * @throws ClassCastException if the class of an element of this list
 654      *         is incompatible with the specified collection
 655      * (<a href="Collection.html#optional-restrictions">optional</a>)
 656      * @throws NullPointerException if this list contains a null element and the
 657      *         specified collection does not permit null elements
 658      * (<a href="Collection.html#optional-restrictions">optional</a>),
 659      *         or if the specified collection is null
 660      * @see Collection#contains(Object)
 661      */
 662     public boolean retainAll(Collection<?> c) {
 663         return batchRemove(c, true);
 664     }
 665 
 666     private boolean batchRemove(Collection<?> c, boolean complement) {
 667         final Object[] elementData = this.elementData;
 668         int r = 0, w = 0;
 669         boolean modified = false;
 670         try {
 671             for (; r < size; r++)
 672                 if (c.contains(elementData[r]) == complement)
 673                     elementData[w++] = elementData[r];
 674         } finally {
 675             // Preserve behavioral compatibility with AbstractCollection,
 676             // even if c.contains() throws.
 677             if (r != size) {
 678                 System.arraycopy(elementData, r,
 679                                  elementData, w,
 680                                  size - r);
 681                 w += size - r;
 682             }
 683             if (w != size) {
 684                 for (int i = w; i < size; i++)
 685                     elementData[i] = null;
 686                 modCount += size - w;
 687                 size = w;
 688                 modified = true;
 689             }
 690         }
 691         return modified;
 692     }
 693 
 694     /**
 695      * Save the state of the <tt>ArrayList</tt> instance to a stream (that
 696      * is, serialize it).
 697      *
 698      * @serialData The length of the array backing the <tt>ArrayList</tt>
 699      *             instance is emitted (int), followed by all of its elements
 700      *             (each an <tt>Object</tt>) in the proper order.
 701      */
 702     private void writeObject(java.io.ObjectOutputStream s)
 703         throws java.io.IOException{
 704         // Write out element count, and any hidden stuff
 705         int expectedModCount = modCount;
 706         s.defaultWriteObject();
 707 
 708         // Write out array length
 709         s.writeInt(elementData.length);
 710 
 711         // Write out all elements in the proper order.
 712         for (int i=0; i<size; i++)
 713             s.writeObject(elementData[i]);
 714 
 715         if (modCount != expectedModCount) {
 716             throw new ConcurrentModificationException();
 717         }
 718 
 719     }
 720 
 721     /**
 722      * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
 723      * deserialize it).
 724      */
 725     private void readObject(java.io.ObjectInputStream s)
 726         throws java.io.IOException, ClassNotFoundException {
 727         // Read in size, and any hidden stuff
 728         s.defaultReadObject();
 729 
 730         // Read in array length and allocate array
 731         int arrayLength = s.readInt();
 732         Object[] a = elementData = new Object[arrayLength];
 733 
 734         // Read in all elements in the proper order.
 735         for (int i=0; i<size; i++)
 736             a[i] = s.readObject();
 737     }
 738 
 739     /**
 740      * Returns a list iterator over the elements in this list (in proper
 741      * sequence), starting at the specified position in the list.
 742      * The specified index indicates the first element that would be
 743      * returned by an initial call to {@link ListIterator#next next}.
 744      * An initial call to {@link ListIterator#previous previous} would
 745      * return the element with the specified index minus one.
 746      *
 747      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 748      *
 749      * @throws IndexOutOfBoundsException {@inheritDoc}
 750      */
 751     public ListIterator<E> listIterator(int index) {
 752         if (index < 0 || index > size)
 753             throw new IndexOutOfBoundsException("Index: "+index);
 754         return new ListItr(index);
 755     }
 756 
 757     /**
 758      * Returns a list iterator over the elements in this list (in proper
 759      * sequence).
 760      *
 761      * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 762      *
 763      * @see #listIterator(int)
 764      */
 765     public ListIterator<E> listIterator() {
 766         return new ListItr(0);
 767     }
 768 
 769     /**
 770      * Returns an iterator over the elements in this list in proper sequence.
 771      *
 772      * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
 773      *
 774      * @return an iterator over the elements in this list in proper sequence
 775      */
 776     public Iterator<E> iterator() {
 777         return new Itr();
 778     }
 779 
 780     /**
 781      * An optimized version of AbstractList.Itr
 782      */
 783     private class Itr implements Iterator<E> {
 784         int cursor;       // index of next element to return
 785         int lastRet = -1; // index of last element returned; -1 if no such
 786         int expectedModCount = modCount;
 787 
 788         public boolean hasNext() {
 789             return cursor != size;
 790         }
 791 
 792         @SuppressWarnings("unchecked")
 793         public E next() {
 794             checkForComodification();
 795             int i = cursor;
 796             if (i >= size)
 797                 throw new NoSuchElementException();
 798             Object[] elementData = ArrayList.this.elementData;
 799             if (i >= elementData.length)
 800                 throw new ConcurrentModificationException();
 801             cursor = i + 1;
 802             return (E) elementData[lastRet = i];
 803         }
 804 
 805         public void remove() {
 806             if (lastRet < 0)
 807                 throw new IllegalStateException();
 808             checkForComodification();
 809 
 810             try {
 811                 ArrayList.this.remove(lastRet);
 812                 cursor = lastRet;
 813                 lastRet = -1;
 814                 expectedModCount = modCount;
 815             } catch (IndexOutOfBoundsException ex) {
 816                 throw new ConcurrentModificationException();
 817             }
 818         }
 819 
 820         final void checkForComodification() {
 821             if (modCount != expectedModCount)
 822                 throw new ConcurrentModificationException();
 823         }
 824     }
 825 
 826     /**
 827      * An optimized version of AbstractList.ListItr
 828      */
 829     private class ListItr extends Itr implements ListIterator<E> {
 830         ListItr(int index) {
 831             super();
 832             cursor = index;
 833         }
 834 
 835         public boolean hasPrevious() {
 836             return cursor != 0;
 837         }
 838 
 839         public int nextIndex() {
 840             return cursor;
 841         }
 842 
 843         public int previousIndex() {
 844             return cursor - 1;
 845         }
 846 
 847         @SuppressWarnings("unchecked")
 848         public E previous() {
 849             checkForComodification();
 850             int i = cursor - 1;
 851             if (i < 0)
 852                 throw new NoSuchElementException();
 853             Object[] elementData = ArrayList.this.elementData;
 854             if (i >= elementData.length)
 855                 throw new ConcurrentModificationException();
 856             cursor = i;
 857             return (E) elementData[lastRet = i];
 858         }
 859 
 860         public void set(E e) {
 861             if (lastRet < 0)
 862                 throw new IllegalStateException();
 863             checkForComodification();
 864 
 865             try {
 866                 ArrayList.this.set(lastRet, e);
 867             } catch (IndexOutOfBoundsException ex) {
 868                 throw new ConcurrentModificationException();
 869             }
 870         }
 871 
 872         public void add(E e) {
 873             checkForComodification();
 874 
 875             try {
 876                 int i = cursor;
 877                 ArrayList.this.add(i, e);
 878                 cursor = i + 1;
 879                 lastRet = -1;
 880                 expectedModCount = modCount;
 881             } catch (IndexOutOfBoundsException ex) {
 882                 throw new ConcurrentModificationException();
 883             }
 884         }
 885     }
 886 
 887     /**
 888      * Returns a view of the portion of this list between the specified
 889      * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.  (If
 890      * {@code fromIndex} and {@code toIndex} are equal, the returned list is
 891      * empty.)  The returned list is backed by this list, so non-structural
 892      * changes in the returned list are reflected in this list, and vice-versa.
 893      * The returned list supports all of the optional list operations.
 894      *
 895      * <p>This method eliminates the need for explicit range operations (of
 896      * the sort that commonly exist for arrays).  Any operation that expects
 897      * a list can be used as a range operation by passing a subList view
 898      * instead of a whole list.  For example, the following idiom
 899      * removes a range of elements from a list:
 900      * <pre>
 901      *      list.subList(from, to).clear();
 902      * </pre>
 903      * Similar idioms may be constructed for {@link #indexOf(Object)} and
 904      * {@link #lastIndexOf(Object)}, and all of the algorithms in the
 905      * {@link Collections} class can be applied to a subList.
 906      *
 907      * <p>The semantics of the list returned by this method become undefined if
 908      * the backing list (i.e., this list) is <i>structurally modified</i> in
 909      * any way other than via the returned list.  (Structural modifications are
 910      * those that change the size of this list, or otherwise perturb it in such
 911      * a fashion that iterations in progress may yield incorrect results.)
 912      *
 913      * @throws IndexOutOfBoundsException {@inheritDoc}
 914      * @throws IllegalArgumentException {@inheritDoc}
 915      */
 916     public List<E> subList(int fromIndex, int toIndex) {
 917         subListRangeCheck(fromIndex, toIndex, size);
 918         return new SubList(this, 0, fromIndex, toIndex);
 919     }
 920 
 921     static void subListRangeCheck(int fromIndex, int toIndex, int size) {
 922         if (fromIndex < 0)
 923             throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
 924         if (toIndex > size)
 925             throw new IndexOutOfBoundsException("toIndex = " + toIndex);
 926         if (fromIndex > toIndex)
 927             throw new IllegalArgumentException("fromIndex(" + fromIndex +
 928                                                ") > toIndex(" + toIndex + ")");
 929     }
 930 
 931     private class SubList extends AbstractList<E> implements RandomAccess {
 932         private final AbstractList<E> parent;
 933         private final int parentOffset;
 934         private final int offset;
 935         int size;
 936 
 937         SubList(AbstractList<E> parent,
 938                 int offset, int fromIndex, int toIndex) {
 939             this.parent = parent;
 940             this.parentOffset = fromIndex;
 941             this.offset = offset + fromIndex;
 942             this.size = toIndex - fromIndex;
 943             this.modCount = ArrayList.this.modCount;
 944         }
 945 
 946         public E set(int index, E e) {
 947             rangeCheck(index);
 948             checkForComodification();
 949             E oldValue = ArrayList.this.elementData(offset + index);
 950             ArrayList.this.elementData[offset + index] = e;
 951             return oldValue;
 952         }
 953 
 954         public E get(int index) {
 955             rangeCheck(index);
 956             checkForComodification();
 957             return ArrayList.this.elementData(offset + index);
 958         }
 959 
 960         public int size() {
 961             checkForComodification();
 962             return this.size;
 963         }
 964 
 965         public void add(int index, E e) {
 966             rangeCheckForAdd(index);
 967             checkForComodification();
 968             parent.add(parentOffset + index, e);
 969             this.modCount = parent.modCount;
 970             this.size++;
 971         }
 972 
 973         public E remove(int index) {
 974             rangeCheck(index);
 975             checkForComodification();
 976             E result = parent.remove(parentOffset + index);
 977             this.modCount = parent.modCount;
 978             this.size--;
 979             return result;
 980         }
 981 
 982         protected void removeRange(int fromIndex, int toIndex) {
 983             checkForComodification();
 984             parent.removeRange(parentOffset + fromIndex,
 985                                parentOffset + toIndex);
 986             this.modCount = parent.modCount;
 987             this.size -= toIndex - fromIndex;
 988         }
 989 
 990         public boolean addAll(Collection<? extends E> c) {
 991             return addAll(this.size, c);
 992         }
 993 
 994         public boolean addAll(int index, Collection<? extends E> c) {
 995             rangeCheckForAdd(index);
 996             int cSize = c.size();
 997             if (cSize==0)
 998                 return false;
 999 
1000             checkForComodification();
1001             parent.addAll(parentOffset + index, c);
1002             this.modCount = parent.modCount;
1003             this.size += cSize;
1004             return true;
1005         }
1006 
1007         public Iterator<E> iterator() {
1008             return listIterator();
1009         }
1010 
1011         public ListIterator<E> listIterator(final int index) {
1012             checkForComodification();
1013             rangeCheckForAdd(index);
1014             final int offset = this.offset;
1015 
1016             return new ListIterator<E>() {
1017                 int cursor = index;
1018                 int lastRet = -1;
1019                 int expectedModCount = ArrayList.this.modCount;
1020 
1021                 public boolean hasNext() {
1022                     return cursor != SubList.this.size;
1023                 }
1024 
1025                 @SuppressWarnings("unchecked")
1026                 public E next() {
1027                     checkForComodification();
1028                     int i = cursor;
1029                     if (i >= SubList.this.size)
1030                         throw new NoSuchElementException();
1031                     Object[] elementData = ArrayList.this.elementData;
1032                     if (offset + i >= elementData.length)
1033                         throw new ConcurrentModificationException();
1034                     cursor = i + 1;
1035                     return (E) elementData[offset + (lastRet = i)];
1036                 }
1037 
1038                 public boolean hasPrevious() {
1039                     return cursor != 0;
1040                 }
1041 
1042                 @SuppressWarnings("unchecked")
1043                 public E previous() {
1044                     checkForComodification();
1045                     int i = cursor - 1;
1046                     if (i < 0)
1047                         throw new NoSuchElementException();
1048                     Object[] elementData = ArrayList.this.elementData;
1049                     if (offset + i >= elementData.length)
1050                         throw new ConcurrentModificationException();
1051                     cursor = i;
1052                     return (E) elementData[offset + (lastRet = i)];
1053                 }
1054 
1055                 public int nextIndex() {
1056                     return cursor;
1057                 }
1058 
1059                 public int previousIndex() {
1060                     return cursor - 1;
1061                 }
1062 
1063                 public void remove() {
1064                     if (lastRet < 0)
1065                         throw new IllegalStateException();
1066                     checkForComodification();
1067 
1068                     try {
1069                         SubList.this.remove(lastRet);
1070                         cursor = lastRet;
1071                         lastRet = -1;
1072                         expectedModCount = ArrayList.this.modCount;
1073                     } catch (IndexOutOfBoundsException ex) {
1074                         throw new ConcurrentModificationException();
1075                     }
1076                 }
1077 
1078                 public void set(E e) {
1079                     if (lastRet < 0)
1080                         throw new IllegalStateException();
1081                     checkForComodification();
1082 
1083                     try {
1084                         ArrayList.this.set(offset + lastRet, e);
1085                     } catch (IndexOutOfBoundsException ex) {
1086                         throw new ConcurrentModificationException();
1087                     }
1088                 }
1089 
1090                 public void add(E e) {
1091                     checkForComodification();
1092 
1093                     try {
1094                         int i = cursor;
1095                         SubList.this.add(i, e);
1096                         cursor = i + 1;
1097                         lastRet = -1;
1098                         expectedModCount = ArrayList.this.modCount;
1099                     } catch (IndexOutOfBoundsException ex) {
1100                         throw new ConcurrentModificationException();
1101                     }
1102                 }
1103 
1104                 final void checkForComodification() {
1105                     if (expectedModCount != ArrayList.this.modCount)
1106                         throw new ConcurrentModificationException();
1107                 }
1108             };
1109         }
1110 
1111         public List<E> subList(int fromIndex, int toIndex) {
1112             subListRangeCheck(fromIndex, toIndex, size);
1113             return new SubList(this, offset, fromIndex, toIndex);
1114         }
1115 
1116         private void rangeCheck(int index) {
1117             if (index < 0 || index >= this.size)
1118                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1119         }
1120 
1121         private void rangeCheckForAdd(int index) {
1122             if (index < 0 || index > this.size)
1123                 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1124         }
1125 
1126         private String outOfBoundsMsg(int index) {
1127             return "Index: "+index+", Size: "+this.size;
1128         }
1129 
1130         private void checkForComodification() {
1131             if (ArrayList.this.modCount != this.modCount)
1132                 throw new ConcurrentModificationException();
1133         }
1134     }
1135 
1136     @Override
1137     public void forEach(Block<? super E> block) {
1138         Objects.requireNonNull(block);
1139         final int expectedModCount = modCount;
1140         final E[] elementData = (E[]) this.elementData;
1141         final int size = this.size;
1142         for (int i=0; modCount == expectedModCount && i < size; i++) {
1143             block.accept(elementData[i]);
1144         }
1145         if (modCount != expectedModCount) {
1146             throw new ConcurrentModificationException();
1147         }
1148     }
1149 
1150     @Override
1151     public boolean removeAll(Predicate<? super E> filter) {
1152         Objects.requireNonNull(filter);
1153         // figure out which elements are to be removed
1154         // any exception thrown from the filter predicate at this stage
1155         // will leave the collection unmodified
1156         int removeCount = 0;
1157         final BitSet removeSet = new BitSet(size);
1158         final int expectedModCount = modCount;
1159         final int size = this.size;
1160         for (int i=0; modCount == expectedModCount && i < size; i++) {
1161             @SuppressWarnings("unchecked")
1162             final E element = (E) elementData[i];
1163             if (filter.test(element)) {
1164                 removeSet.set(i);
1165                 removeCount++;
1166             }
1167         }
1168 
1169         if (modCount != expectedModCount) {
1170             throw new ConcurrentModificationException();
1171         }
1172 
1173         // shift surviving elements left over the spaces left by removed elements
1174         final boolean anyToRemove = removeCount > 0;
1175         if (anyToRemove) {
1176             final int newSize = size - removeCount;
1177             for (int i=0, j=0; modCount == expectedModCount &&
1178                     (i < size) && (j < newSize); i++, j++) {
1179                 i = removeSet.nextClearBit(i);
1180                 elementData[j] = elementData[i];
1181             }
1182             for (int k=newSize; modCount == expectedModCount && k < size; k++) {
1183                 elementData[k] = null;  // Let gc do its work
1184             }
1185             this.size = newSize;
1186             if (modCount != expectedModCount) {
1187                 throw new ConcurrentModificationException();
1188             }
1189             modCount++;
1190         }
1191 
1192         return anyToRemove;
1193     }
1194 
1195     @Override
1196     @SuppressWarnings("unchecked")
1197     public void replaceAll(UnaryOperator<E> operator) {
1198         Objects.requireNonNull(operator);
1199         final int expectedModCount = modCount;
1200         final int size = this.size;
1201         for (int i=0; modCount == expectedModCount && i < size; i++) {
1202             elementData[i] = operator.operate((E) elementData[i]);
1203         }
1204         if (modCount != expectedModCount) {
1205             throw new ConcurrentModificationException();
1206         }
1207         modCount++;
1208     }
1209 
1210     @Override
1211     @SuppressWarnings("unchecked")
1212     public void sort(Comparator<? super E> c) {
1213         Objects.requireNonNull(c);
1214         final int expectedModCount = modCount;
1215         Arrays.sort((E[]) elementData, 0, size, c);
1216         if (modCount != expectedModCount) {
1217             throw new ConcurrentModificationException();
1218         }
1219         modCount++;
1220     }
1221 }