src/share/classes/java/util/ArrayList.java

Print this page
rev 9490 : 8035584: ArrayList(c) should avoid inflation if c is empty
Reviewed-by: martin


  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>:</a>
  76  * if the list is structurally modified at any time after the iterator is
  77  * created, in any way except through the iterator's own
  78  * {@link ListIterator#remove() remove} or
  79  * {@link ListIterator#add(Object) add} methods, the iterator will throw a
  80  * {@link ConcurrentModificationException}.  Thus, in the face of
  81  * concurrent modification, the iterator fails quickly and cleanly, rather
  82  * than risking arbitrary, non-deterministic behavior at an undetermined
  83  * time in the future.
  84  *
  85  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  86  * as it is, generally speaking, impossible to make any hard guarantees in the
  87  * presence of unsynchronized concurrent modification.  Fail-fast iterators
  88  * throw {@code ConcurrentModificationException} on a best-effort basis.
  89  * Therefore, it would be wrong to write a program that depended on this
  90  * exception for its correctness:  <i>the fail-fast behavior of iterators
  91  * should be used only to detect bugs.</i>
  92  *
  93  * <p>This class is a member of the
  94  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  95  * Java Collections Framework</a>.
  96  *


  97  * @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      */


 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;


 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!!


 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


 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 


 709             // even if c.contains() throws.
 710             if (r != size) {
 711                 System.arraycopy(elementData, r,
 712                                  elementData, w,
 713                                  size - r);
 714                 w += size - r;
 715             }
 716             if (w != size) {
 717                 // clear to let GC do its work
 718                 for (int i = w; i < size; i++)
 719                     elementData[i] = null;
 720                 modCount += size - w;
 721                 size = w;
 722                 modified = true;
 723             }
 724         }
 725         return modified;
 726     }
 727 
 728     /**
 729      * Save the state of the <tt>ArrayList</tt> instance to a stream (that
 730      * is, serialize it).
 731      *
 732      * @serialData The length of the array backing the <tt>ArrayList</tt>
 733      *             instance is emitted (int), followed by all of its elements
 734      *             (each an <tt>Object</tt>) in the proper order.
 735      */
 736     private void writeObject(java.io.ObjectOutputStream s)
 737         throws java.io.IOException{
 738         // Write out element count, and any hidden stuff
 739         int expectedModCount = modCount;
 740         s.defaultWriteObject();
 741 
 742         // Write out size as capacity for behavioural compatibility with clone()
 743         s.writeInt(size);
 744 
 745         // Write out all elements in the proper order.
 746         for (int i=0; i<size; i++) {
 747             s.writeObject(elementData[i]);
 748         }
 749 
 750         if (modCount != expectedModCount) {
 751             throw new ConcurrentModificationException();
 752         }
 753     }
 754 
 755     /**
 756      * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
 757      * deserialize it).
 758      */
 759     private void readObject(java.io.ObjectInputStream s)
 760         throws java.io.IOException, ClassNotFoundException {
 761         elementData = EMPTY_ELEMENTDATA;
 762 
 763         // Read in size, and any hidden stuff
 764         s.defaultReadObject();
 765 
 766         // Read in capacity
 767         s.readInt(); // ignored
 768 
 769         if (size > 0) {
 770             // be like clone(), allocate array based upon size not capacity
 771             ensureCapacityInternal(size);
 772 
 773             Object[] a = elementData;
 774             // Read in all elements in the proper order.
 775             for (int i=0; i<size; i++) {
 776                 a[i] = s.readObject();




  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.util;
  27 
  28 import java.util.function.Consumer;
  29 import java.util.function.Predicate;
  30 import java.util.function.UnaryOperator;
  31 
  32 /**
  33  * Resizable-array implementation of the {@code List} interface.  Implements
  34  * all optional list operations, and permits all elements, including
  35  * {@code null}.  In addition to implementing the {@code List} interface,
  36  * this class provides methods to manipulate the size of the array that is
  37  * used internally to store the list.  (This class is roughly equivalent to
  38  * {@code Vector}, except that it is unsynchronized.)
  39  *
  40  * <p>The {@code size}, {@code isEmpty}, {@code get}, {@code set},
  41  * {@code iterator}, and {@code listIterator} operations run in constant
  42  * time.  The {@code add} operation runs in <i>amortized constant time</i>,
  43  * that is, adding n elements requires O(n) time.  All of the other operations
  44  * run in linear time (roughly speaking).  The constant factor is low compared
  45  * to that for the {@code LinkedList} implementation.
  46  *
  47  * <p>Each {@code ArrayList} instance has a <i>capacity</i>.  The capacity is
  48  * the size of the array used to store the elements in the list.  It is always
  49  * at least as large as the list size.  As elements are added to an ArrayList,
  50  * its capacity grows automatically.  The details of the growth policy are not
  51  * specified beyond the fact that adding an element has constant amortized
  52  * time cost.
  53  *
  54  * <p>An application can increase the capacity of an {@code ArrayList} instance
  55  * before adding a large number of elements using the {@code ensureCapacity}
  56  * operation.  This may reduce the amount of incremental reallocation.
  57  *
  58  * <p><strong>Note that this implementation is not synchronized.</strong>
  59  * If multiple threads access an {@code ArrayList} instance concurrently,
  60  * and at least one of the threads modifies the list structurally, it
  61  * <i>must</i> be synchronized externally.  (A structural modification is
  62  * any operation that adds or deletes one or more elements, or explicitly
  63  * resizes the backing array; merely setting the value of an element is not
  64  * a structural modification.)  This is typically accomplished by
  65  * synchronizing on some object that naturally encapsulates the list.
  66  *
  67  * If no such object exists, the list should be "wrapped" using the
  68  * {@link Collections#synchronizedList Collections.synchronizedList}
  69  * method.  This is best done at creation time, to prevent accidental
  70  * unsynchronized access to the list:<pre>
  71  *   List list = Collections.synchronizedList(new ArrayList(...));</pre>
  72  *
  73  * <p><a name="fail-fast">
  74  * The iterators returned by this class's {@link #iterator() iterator} and
  75  * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:</a>
  76  * if the list is structurally modified at any time after the iterator is
  77  * created, in any way except through the iterator's own
  78  * {@link ListIterator#remove() remove} or
  79  * {@link ListIterator#add(Object) add} methods, the iterator will throw a
  80  * {@link ConcurrentModificationException}.  Thus, in the face of
  81  * concurrent modification, the iterator fails quickly and cleanly, rather
  82  * than risking arbitrary, non-deterministic behavior at an undetermined
  83  * time in the future.
  84  *
  85  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
  86  * as it is, generally speaking, impossible to make any hard guarantees in the
  87  * presence of unsynchronized concurrent modification.  Fail-fast iterators
  88  * throw {@code ConcurrentModificationException} on a best-effort basis.
  89  * Therefore, it would be wrong to write a program that depended on this
  90  * exception for its correctness:  <i>the fail-fast behavior of iterators
  91  * should be used only to detect bugs.</i>
  92  *
  93  * <p>This class is a member of the
  94  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  95  * Java Collections Framework</a>.
  96  *
  97  * @param <E> the type of elements in this list
  98  *
  99  * @author  Josh Bloch
 100  * @author  Neal Gafter
 101  * @see     Collection
 102  * @see     List
 103  * @see     LinkedList
 104  * @see     Vector
 105  * @since   1.2
 106  */
 107 
 108 public class ArrayList<E> extends AbstractList<E>
 109         implements List<E>, RandomAccess, Cloneable, java.io.Serializable
 110 {
 111     private static final long serialVersionUID = 8683452581122892189L;
 112 
 113     /**
 114      * Default initial capacity.
 115      */
 116     private static final int DEFAULT_CAPACITY = 10;
 117 
 118     /**
 119      * Shared empty array instance used for empty instances.
 120      */
 121     private static final Object[] EMPTY_ELEMENTDATA = {};
 122 
 123     /**
 124      * Shared empty array instance used for default sized empty instances. We
 125      * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
 126      * first element is added.
 127      */
 128     private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
 129 
 130     /**
 131      * The array buffer into which the elements of the ArrayList are stored.
 132      * The capacity of the ArrayList is the length of this array buffer. Any
 133      * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
 134      * will be expanded to DEFAULT_CAPACITY when the first element is added.
 135      */
 136     transient Object[] elementData; // non-private to simplify nested class access
 137 
 138     /**
 139      * The size of the ArrayList (the number of elements it contains).
 140      *
 141      * @serial
 142      */
 143     private int size;
 144 
 145     /**
 146      * Constructs an empty list with the specified initial capacity.
 147      *
 148      * @param  initialCapacity  the initial capacity of the list
 149      * @throws IllegalArgumentException if the specified initial capacity
 150      *         is negative
 151      */
 152     public ArrayList(int initialCapacity) {
 153         if (initialCapacity > 0) {
 154             this.elementData = new Object[initialCapacity];
 155         } else if (initialCapacity == 0) {
 156             this.elementData = EMPTY_ELEMENTDATA;
 157         } else {
 158             throw new IllegalArgumentException("Illegal Capacity: "+
 159                                                initialCapacity);
 160         }
 161     }
 162 
 163     /**
 164      * Constructs an empty list with an initial capacity of ten.
 165      */
 166     public ArrayList() {
 167         this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;

 168     }
 169 
 170     /**
 171      * Constructs a list containing the elements of the specified
 172      * collection, in the order they are returned by the collection's
 173      * iterator.
 174      *
 175      * @param c the collection whose elements are to be placed into this list
 176      * @throws NullPointerException if the specified collection is null
 177      */
 178     public ArrayList(Collection<? extends E> c) {
 179         elementData = c.toArray();
 180         if ((size = elementData.length) != 0) {
 181             // c.toArray might (incorrectly) not return Object[] (see 6260652)
 182             if (elementData.getClass() != Object[].class)
 183                 elementData = Arrays.copyOf(elementData, size, Object[].class);
 184         } else {
 185             // replace with empty array.
 186             this.elementData = EMPTY_ELEMENTDATA;
 187         }
 188     }
 189 
 190     /**
 191      * Trims the capacity of this {@code ArrayList} instance to be the
 192      * list's current size.  An application can use this operation to minimize
 193      * the storage of an {@code ArrayList} instance.
 194      */
 195     public void trimToSize() {
 196         modCount++;
 197         if (size < elementData.length) {
 198             elementData = (size == 0)
 199               ? EMPTY_ELEMENTDATA
 200               : Arrays.copyOf(elementData, size);
 201         }
 202     }
 203 
 204     /**
 205      * Increases the capacity of this {@code ArrayList} instance, if
 206      * necessary, to ensure that it can hold at least the number of elements
 207      * specified by the minimum capacity argument.
 208      *
 209      * @param   minCapacity   the desired minimum capacity
 210      */
 211     public void ensureCapacity(int minCapacity) {
 212         int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
 213             // any size if not default element table
 214             ? 0
 215             // larger than default for default empty table. It's already
 216             // supposed to be at default size.
 217             : DEFAULT_CAPACITY;
 218 
 219         if (minCapacity > minExpand) {
 220             ensureExplicitCapacity(minCapacity);
 221         }
 222     }
 223 
 224     private void ensureCapacityInternal(int minCapacity) {
 225         if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
 226             minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
 227         }
 228 
 229         ensureExplicitCapacity(minCapacity);
 230     }
 231 
 232     private void ensureExplicitCapacity(int minCapacity) {
 233         modCount++;
 234 
 235         // overflow-conscious code
 236         if (minCapacity - elementData.length > 0)
 237             grow(minCapacity);
 238     }
 239 
 240     /**
 241      * The maximum size of array to allocate.
 242      * Some VMs reserve some header words in an array.
 243      * Attempts to allocate larger arrays may result in
 244      * OutOfMemoryError: Requested array size exceeds VM limit
 245      */


 264     }
 265 
 266     private static int hugeCapacity(int minCapacity) {
 267         if (minCapacity < 0) // overflow
 268             throw new OutOfMemoryError();
 269         return (minCapacity > MAX_ARRAY_SIZE) ?
 270             Integer.MAX_VALUE :
 271             MAX_ARRAY_SIZE;
 272     }
 273 
 274     /**
 275      * Returns the number of elements in this list.
 276      *
 277      * @return the number of elements in this list
 278      */
 279     public int size() {
 280         return size;
 281     }
 282 
 283     /**
 284      * Returns {@code true} if this list contains no elements.
 285      *
 286      * @return {@code true} if this list contains no elements
 287      */
 288     public boolean isEmpty() {
 289         return size == 0;
 290     }
 291 
 292     /**
 293      * Returns {@code true} if this list contains the specified element.
 294      * More formally, returns {@code true} if and only if this list contains
 295      * at least one element {@code e} such that
 296      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
 297      *
 298      * @param o element whose presence in this list is to be tested
 299      * @return {@code true} if this list contains the specified element
 300      */
 301     public boolean contains(Object o) {
 302         return indexOf(o) >= 0;
 303     }
 304 
 305     /**
 306      * Returns the index of the first occurrence of the specified element
 307      * in this list, or -1 if this list does not contain the element.
 308      * More formally, returns the lowest index {@code i} such that
 309      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
 310      * or -1 if there is no such index.
 311      */
 312     public int indexOf(Object o) {
 313         if (o == null) {
 314             for (int i = 0; i < size; i++)
 315                 if (elementData[i]==null)
 316                     return i;
 317         } else {
 318             for (int i = 0; i < size; i++)
 319                 if (o.equals(elementData[i]))
 320                     return i;
 321         }
 322         return -1;
 323     }
 324 
 325     /**
 326      * Returns the index of the last occurrence of the specified element
 327      * in this list, or -1 if this list does not contain the element.
 328      * More formally, returns the highest index {@code i} such that
 329      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
 330      * or -1 if there is no such index.
 331      */
 332     public int lastIndexOf(Object o) {
 333         if (o == null) {
 334             for (int i = size-1; i >= 0; i--)
 335                 if (elementData[i]==null)
 336                     return i;
 337         } else {
 338             for (int i = size-1; i >= 0; i--)
 339                 if (o.equals(elementData[i]))
 340                     return i;
 341         }
 342         return -1;
 343     }
 344 
 345     /**
 346      * Returns a shallow copy of this {@code ArrayList} instance.  (The
 347      * elements themselves are not copied.)
 348      *
 349      * @return a clone of this {@code ArrayList} instance
 350      */
 351     public Object clone() {
 352         try {
 353             ArrayList<?> v = (ArrayList<?>) super.clone();
 354             v.elementData = Arrays.copyOf(elementData, size);
 355             v.modCount = 0;
 356             return v;
 357         } catch (CloneNotSupportedException e) {
 358             // this shouldn't happen, since we are Cloneable
 359             throw new InternalError(e);
 360         }
 361     }
 362 
 363     /**
 364      * Returns an array containing all of the elements in this list
 365      * in proper sequence (from first to last element).
 366      *
 367      * <p>The returned array will be "safe" in that no references to it are
 368      * maintained by this list.  (In other words, this method must allocate
 369      * a new array).  The caller is thus free to modify the returned array.
 370      *
 371      * <p>This method acts as bridge between array-based and collection-based
 372      * APIs.
 373      *
 374      * @return an array containing all of the elements in this list in
 375      *         proper sequence
 376      */
 377     public Object[] toArray() {
 378         int sz = size;
 379         return (sz != 0)
 380             ? Arrays.copyOf(elementData, sz)
 381             : EMPTY_ELEMENTDATA;
 382     }
 383 
 384     /**
 385      * Returns an array containing all of the elements in this list in proper
 386      * sequence (from first to last element); the runtime type of the returned
 387      * array is that of the specified array.  If the list fits in the
 388      * specified array, it is returned therein.  Otherwise, a new array is
 389      * allocated with the runtime type of the specified array and the size of
 390      * this list.
 391      *
 392      * <p>If the list fits in the specified array with room to spare
 393      * (i.e., the array has more elements than the list), the element in
 394      * the array immediately following the end of the collection is set to
 395      * {@code null}.  (This is useful in determining the length of the
 396      * list <i>only</i> if the caller knows that the list does not contain
 397      * any null elements.)
 398      *
 399      * @param a the array into which the elements of the list are to
 400      *          be stored, if it is big enough; otherwise, a new array of the
 401      *          same runtime type is allocated for this purpose.
 402      * @return an array containing the elements of the list
 403      * @throws ArrayStoreException if the runtime type of the specified array
 404      *         is not a supertype of the runtime type of every element in
 405      *         this list
 406      * @throws NullPointerException if the specified array is null
 407      */
 408     @SuppressWarnings("unchecked")
 409     public <T> T[] toArray(T[] a) {
 410         if (a.length < size)
 411             // Make a new array of a's runtime type, but my contents:
 412             return (T[]) Arrays.copyOf(elementData, size, a.getClass());
 413         System.arraycopy(elementData, 0, a, 0, size);
 414         if (a.length > size)
 415             a[size] = null;


 440      * Replaces the element at the specified position in this list with
 441      * the specified element.
 442      *
 443      * @param index index of the element to replace
 444      * @param element element to be stored at the specified position
 445      * @return the element previously at the specified position
 446      * @throws IndexOutOfBoundsException {@inheritDoc}
 447      */
 448     public E set(int index, E element) {
 449         rangeCheck(index);
 450 
 451         E oldValue = elementData(index);
 452         elementData[index] = element;
 453         return oldValue;
 454     }
 455 
 456     /**
 457      * Appends the specified element to the end of this list.
 458      *
 459      * @param e element to be appended to this list
 460      * @return {@code true} (as specified by {@link Collection#add})
 461      */
 462     public boolean add(E e) {
 463         ensureCapacityInternal(size + 1);  // Increments modCount!!
 464         elementData[size++] = e;
 465         return true;
 466     }
 467 
 468     /**
 469      * Inserts the specified element at the specified position in this
 470      * list. Shifts the element currently at that position (if any) and
 471      * any subsequent elements to the right (adds one to their indices).
 472      *
 473      * @param index index at which the specified element is to be inserted
 474      * @param element element to be inserted
 475      * @throws IndexOutOfBoundsException {@inheritDoc}
 476      */
 477     public void add(int index, E element) {
 478         rangeCheckForAdd(index);
 479 
 480         ensureCapacityInternal(size + 1);  // Increments modCount!!


 495      */
 496     public E remove(int index) {
 497         rangeCheck(index);
 498 
 499         modCount++;
 500         E oldValue = elementData(index);
 501 
 502         int numMoved = size - index - 1;
 503         if (numMoved > 0)
 504             System.arraycopy(elementData, index+1, elementData, index,
 505                              numMoved);
 506         elementData[--size] = null; // clear to let GC do its work
 507 
 508         return oldValue;
 509     }
 510 
 511     /**
 512      * Removes the first occurrence of the specified element from this list,
 513      * if it is present.  If the list does not contain the element, it is
 514      * unchanged.  More formally, removes the element with the lowest index
 515      * {@code i} such that
 516      * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
 517      * (if such an element exists).  Returns {@code true} if this list
 518      * contained the specified element (or equivalently, if this list
 519      * changed as a result of the call).
 520      *
 521      * @param o element to be removed from this list, if present
 522      * @return {@code true} if this list contained the specified element
 523      */
 524     public boolean remove(Object o) {
 525         if (o == null) {
 526             for (int index = 0; index < size; index++)
 527                 if (elementData[index] == null) {
 528                     fastRemove(index);
 529                     return true;
 530                 }
 531         } else {
 532             for (int index = 0; index < size; index++)
 533                 if (o.equals(elementData[index])) {
 534                     fastRemove(index);
 535                     return true;
 536                 }
 537         }
 538         return false;
 539     }
 540 
 541     /*
 542      * Private remove method that skips bounds checking and does not


 558     public void clear() {
 559         modCount++;
 560 
 561         // clear to let GC do its work
 562         for (int i = 0; i < size; i++)
 563             elementData[i] = null;
 564 
 565         size = 0;
 566     }
 567 
 568     /**
 569      * Appends all of the elements in the specified collection to the end of
 570      * this list, in the order that they are returned by the
 571      * specified collection's Iterator.  The behavior of this operation is
 572      * undefined if the specified collection is modified while the operation
 573      * is in progress.  (This implies that the behavior of this call is
 574      * undefined if the specified collection is this list, and this
 575      * list is nonempty.)
 576      *
 577      * @param c collection containing elements to be added to this list
 578      * @return {@code true} if this list changed as a result of the call
 579      * @throws NullPointerException if the specified collection is null
 580      */
 581     public boolean addAll(Collection<? extends E> c) {
 582         Object[] a = c.toArray();
 583         int numNew = a.length;
 584         ensureCapacityInternal(size + numNew);  // Increments modCount
 585         System.arraycopy(a, 0, elementData, size, numNew);
 586         size += numNew;
 587         return numNew != 0;
 588     }
 589 
 590     /**
 591      * Inserts all of the elements in the specified collection into this
 592      * list, starting at the specified position.  Shifts the element
 593      * currently at that position (if any) and any subsequent elements to
 594      * the right (increases their indices).  The new elements will appear
 595      * in the list in the order that they are returned by the
 596      * specified collection's iterator.
 597      *
 598      * @param index index at which to insert the first element from the
 599      *              specified collection
 600      * @param c collection containing elements to be added to this list
 601      * @return {@code true} if this list changed as a result of the call
 602      * @throws IndexOutOfBoundsException {@inheritDoc}
 603      * @throws NullPointerException if the specified collection is null
 604      */
 605     public boolean addAll(int index, Collection<? extends E> c) {
 606         rangeCheckForAdd(index);
 607 
 608         Object[] a = c.toArray();
 609         int numNew = a.length;
 610         ensureCapacityInternal(size + numNew);  // Increments modCount
 611 
 612         int numMoved = size - index;
 613         if (numMoved > 0)
 614             System.arraycopy(elementData, index, elementData, index + numNew,
 615                              numMoved);
 616 
 617         System.arraycopy(a, 0, elementData, index, numNew);
 618         size += numNew;
 619         return numNew != 0;
 620     }
 621 


 729             // even if c.contains() throws.
 730             if (r != size) {
 731                 System.arraycopy(elementData, r,
 732                                  elementData, w,
 733                                  size - r);
 734                 w += size - r;
 735             }
 736             if (w != size) {
 737                 // clear to let GC do its work
 738                 for (int i = w; i < size; i++)
 739                     elementData[i] = null;
 740                 modCount += size - w;
 741                 size = w;
 742                 modified = true;
 743             }
 744         }
 745         return modified;
 746     }
 747 
 748     /**
 749      * Save the state of the {@code ArrayList} instance to a stream (that
 750      * is, serialize it).
 751      *
 752      * @serialData The length of the array backing the {@code ArrayList}
 753      *             instance is emitted (int), followed by all of its elements
 754      *             (each an {@code Object}) in the proper order.
 755      */
 756     private void writeObject(java.io.ObjectOutputStream s)
 757         throws java.io.IOException{
 758         // Write out element count, and any hidden stuff
 759         int expectedModCount = modCount;
 760         s.defaultWriteObject();
 761 
 762         // Write out size as capacity for behavioural compatibility with clone()
 763         s.writeInt(size);
 764 
 765         // Write out all elements in the proper order.
 766         for (int i=0; i<size; i++) {
 767             s.writeObject(elementData[i]);
 768         }
 769 
 770         if (modCount != expectedModCount) {
 771             throw new ConcurrentModificationException();
 772         }
 773     }
 774 
 775     /**
 776      * Reconstitute the {@code ArrayList} instance from a stream (that is,
 777      * deserialize it).
 778      */
 779     private void readObject(java.io.ObjectInputStream s)
 780         throws java.io.IOException, ClassNotFoundException {
 781         elementData = EMPTY_ELEMENTDATA;
 782 
 783         // Read in size, and any hidden stuff
 784         s.defaultReadObject();
 785 
 786         // Read in capacity
 787         s.readInt(); // ignored
 788 
 789         if (size > 0) {
 790             // be like clone(), allocate array based upon size not capacity
 791             ensureCapacityInternal(size);
 792 
 793             Object[] a = elementData;
 794             // Read in all elements in the proper order.
 795             for (int i=0; i<size; i++) {
 796                 a[i] = s.readObject();