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