ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayList.java
(Generate patch)

Comparing jsr166/src/main/java/util/ArrayList.java (file contents):
Revision 1.28 by jsr166, Mon May 19 00:32:45 2008 UTC vs.
Revision 1.51 by jsr166, Sun May 14 21:44:25 2017 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
2 > * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
3   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5   * This code is free software; you can redistribute it and/or modify it
6   * under the terms of the GNU General Public License version 2 only, as
7 < * published by the Free Software Foundation.  Sun designates this
7 > * published by the Free Software Foundation.  Oracle designates this
8   * particular file as subject to the "Classpath" exception as provided
9 < * by Sun in the LICENSE file that accompanied this code.
9 > * by Oracle in the LICENSE file that accompanied this code.
10   *
11   * This code is distributed in the hope that it will be useful, but WITHOUT
12   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# Line 18 | Line 18
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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
22 < * CA 95054 USA or visit www.sun.com if you need additional information or
23 < * have any questions.
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
33 > * Resizable-array implementation of the {@code List} 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,
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 < * <tt>Vector</tt>, except that it is unsynchronized.)
38 > * {@code Vector}, 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>,
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 <tt>LinkedList</tt> implementation.
45 > * to that for the {@code LinkedList} implementation.
46   *
47 < * <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>.  The capacity is
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 <tt>ArrayList</tt> instance
55 < * before adding a large number of elements using the <tt>ensureCapacity</tt>
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 <tt>ArrayList</tt> instance concurrently,
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
# Line 66 | Line 70 | package java.util;
70   * unsynchronized access to the list:<pre>
71   *   List list = Collections.synchronizedList(new ArrayList(...));</pre>
72   *
73 < * <p><a name="fail-fast"/>
73 > * <p id="fail-fast">
74   * The iterators returned by this class's {@link #iterator() iterator} and
75   * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
76   * if the list is structurally modified at any time after the iterator is
# Line 87 | Line 91 | package java.util;
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">
94 > * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
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
# Line 98 | Line 104 | package java.util;
104   * @see     Vector
105   * @since   1.2
106   */
101
107   public class ArrayList<E> extends AbstractList<E>
108          implements List<E>, RandomAccess, Cloneable, java.io.Serializable
109   {
110      private static final long serialVersionUID = 8683452581122892189L;
111  
112      /**
113 +     * Default initial capacity.
114 +     */
115 +    private static final int DEFAULT_CAPACITY = 10;
116 +
117 +    /**
118 +     * Shared empty array instance used for empty instances.
119 +     */
120 +    private static final Object[] EMPTY_ELEMENTDATA = {};
121 +
122 +    /**
123 +     * Shared empty array instance used for default sized empty instances. We
124 +     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
125 +     * first element is added.
126 +     */
127 +    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
128 +
129 +    /**
130       * The array buffer into which the elements of the ArrayList are stored.
131 <     * The capacity of the ArrayList is the length of this array buffer.
131 >     * The capacity of the ArrayList is the length of this array buffer. Any
132 >     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
133 >     * will be expanded to DEFAULT_CAPACITY when the first element is added.
134       */
135 <    private transient Object[] elementData;
135 >    transient Object[] elementData; // non-private to simplify nested class access
136  
137      /**
138       * The size of the ArrayList (the number of elements it contains).
# Line 120 | Line 144 | public class ArrayList<E> extends Abstra
144      /**
145       * Constructs an empty list with the specified initial capacity.
146       *
147 <     * @param   initialCapacity   the initial capacity of the list
148 <     * @exception IllegalArgumentException if the specified initial capacity
149 <     *            is negative
147 >     * @param  initialCapacity  the initial capacity of the list
148 >     * @throws IllegalArgumentException if the specified initial capacity
149 >     *         is negative
150       */
151      public ArrayList(int initialCapacity) {
152 <        super();
153 <        if (initialCapacity < 0)
152 >        if (initialCapacity > 0) {
153 >            this.elementData = new Object[initialCapacity];
154 >        } else if (initialCapacity == 0) {
155 >            this.elementData = EMPTY_ELEMENTDATA;
156 >        } else {
157              throw new IllegalArgumentException("Illegal Capacity: "+
158                                                 initialCapacity);
159 <        this.elementData = new Object[initialCapacity];
159 >        }
160      }
161  
162      /**
163       * Constructs an empty list with an initial capacity of ten.
164       */
165      public ArrayList() {
166 <        this(10);
166 >        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
167      }
168  
169      /**
# Line 149 | Line 176 | public class ArrayList<E> extends Abstra
176       */
177      public ArrayList(Collection<? extends E> c) {
178          elementData = c.toArray();
179 <        size = elementData.length;
180 <        // c.toArray might (incorrectly) not return Object[] (see 6260652)
181 <        if (elementData.getClass() != Object[].class)
182 <            elementData = Arrays.copyOf(elementData, size, Object[].class);
179 >        if ((size = elementData.length) != 0) {
180 >            // defend against c.toArray (incorrectly) not returning Object[]
181 >            // (see e.g. https://bugs.openjdk.java.net/browse/JDK-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 <tt>ArrayList</tt> instance to be the
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 <tt>ArrayList</tt> instance.
193 >     * the storage of an {@code ArrayList} instance.
194       */
195      public void trimToSize() {
196          modCount++;
197 <        int oldCapacity = elementData.length;
198 <        if (size < oldCapacity) {
199 <            elementData = Arrays.copyOf(elementData, size);
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 <tt>ArrayList</tt> instance, if
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
209 >     * @param minCapacity the desired minimum capacity
210       */
211      public void ensureCapacity(int minCapacity) {
212 <        modCount++;
213 <        int oldCapacity = elementData.length;
214 <        if (minCapacity > oldCapacity) {
215 <            Object oldData[] = elementData;
216 <            int newCapacity = (oldCapacity * 3)/2 + 1;
184 <            if (newCapacity < minCapacity)
185 <                newCapacity = minCapacity;
186 <            // minCapacity is usually close to size, so this is a win:
187 <            elementData = Arrays.copyOf(elementData, newCapacity);
212 >        if (minCapacity > elementData.length
213 >            && !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
214 >                 && minCapacity <= DEFAULT_CAPACITY)) {
215 >            modCount++;
216 >            grow(minCapacity);
217          }
218      }
219  
220      /**
221 +     * The maximum size of array to allocate (unless necessary).
222 +     * Some VMs reserve some header words in an array.
223 +     * Attempts to allocate larger arrays may result in
224 +     * OutOfMemoryError: Requested array size exceeds VM limit
225 +     */
226 +    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
227 +
228 +    /**
229 +     * Increases the capacity to ensure that it can hold at least the
230 +     * number of elements specified by the minimum capacity argument.
231 +     *
232 +     * @param minCapacity the desired minimum capacity
233 +     * @throws OutOfMemoryError if minCapacity is less than zero
234 +     */
235 +    private Object[] grow(int minCapacity) {
236 +        return elementData = Arrays.copyOf(elementData,
237 +                                           newCapacity(minCapacity));
238 +    }
239 +
240 +    private Object[] grow() {
241 +        return grow(size + 1);
242 +    }
243 +
244 +    /**
245 +     * Returns a capacity at least as large as the given minimum capacity.
246 +     * Returns the current capacity increased by 50% if that suffices.
247 +     * Will not return a capacity greater than MAX_ARRAY_SIZE unless
248 +     * the given minimum capacity is greater than MAX_ARRAY_SIZE.
249 +     *
250 +     * @param minCapacity the desired minimum capacity
251 +     * @throws OutOfMemoryError if minCapacity is less than zero
252 +     */
253 +    private int newCapacity(int minCapacity) {
254 +        // overflow-conscious code
255 +        int oldCapacity = elementData.length;
256 +        int newCapacity = oldCapacity + (oldCapacity >> 1);
257 +        if (newCapacity - minCapacity <= 0) {
258 +            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
259 +                return Math.max(DEFAULT_CAPACITY, minCapacity);
260 +            if (minCapacity < 0) // overflow
261 +                throw new OutOfMemoryError();
262 +            return minCapacity;
263 +        }
264 +        return (newCapacity - MAX_ARRAY_SIZE <= 0)
265 +            ? newCapacity
266 +            : hugeCapacity(minCapacity);
267 +    }
268 +
269 +    private static int hugeCapacity(int minCapacity) {
270 +        if (minCapacity < 0) // overflow
271 +            throw new OutOfMemoryError();
272 +        return (minCapacity > MAX_ARRAY_SIZE)
273 +            ? Integer.MAX_VALUE
274 +            : MAX_ARRAY_SIZE;
275 +    }
276 +
277 +    /**
278       * Returns the number of elements in this list.
279       *
280       * @return the number of elements in this list
# Line 198 | Line 284 | public class ArrayList<E> extends Abstra
284      }
285  
286      /**
287 <     * Returns <tt>true</tt> if this list contains no elements.
287 >     * Returns {@code true} if this list contains no elements.
288       *
289 <     * @return <tt>true</tt> if this list contains no elements
289 >     * @return {@code true} if this list contains no elements
290       */
291      public boolean isEmpty() {
292          return size == 0;
293      }
294  
295      /**
296 <     * Returns <tt>true</tt> if this list contains the specified element.
297 <     * More formally, returns <tt>true</tt> if and only if this list contains
298 <     * at least one element <tt>e</tt> such that
299 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
296 >     * Returns {@code true} if this list contains the specified element.
297 >     * More formally, returns {@code true} if and only if this list contains
298 >     * at least one element {@code e} such that
299 >     * {@code Objects.equals(o, e)}.
300       *
301       * @param o element whose presence in this list is to be tested
302 <     * @return <tt>true</tt> if this list contains the specified element
302 >     * @return {@code true} if this list contains the specified element
303       */
304      public boolean contains(Object o) {
305          return indexOf(o) >= 0;
# Line 222 | Line 308 | public class ArrayList<E> extends Abstra
308      /**
309       * Returns the index of the first occurrence of the specified element
310       * in this list, or -1 if this list does not contain the element.
311 <     * More formally, returns the lowest index <tt>i</tt> such that
312 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
311 >     * More formally, returns the lowest index {@code i} such that
312 >     * {@code Objects.equals(o, get(i))},
313       * or -1 if there is no such index.
314       */
315      public int indexOf(Object o) {
# Line 242 | Line 328 | public class ArrayList<E> extends Abstra
328      /**
329       * Returns the index of the last occurrence of the specified element
330       * in this list, or -1 if this list does not contain the element.
331 <     * More formally, returns the highest index <tt>i</tt> such that
332 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
331 >     * More formally, returns the highest index {@code i} such that
332 >     * {@code Objects.equals(o, get(i))},
333       * or -1 if there is no such index.
334       */
335      public int lastIndexOf(Object o) {
# Line 260 | Line 346 | public class ArrayList<E> extends Abstra
346      }
347  
348      /**
349 <     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
349 >     * Returns a shallow copy of this {@code ArrayList} instance.  (The
350       * elements themselves are not copied.)
351       *
352 <     * @return a clone of this <tt>ArrayList</tt> instance
352 >     * @return a clone of this {@code ArrayList} instance
353       */
354      public Object clone() {
355          try {
356 <            @SuppressWarnings("unchecked")
271 <                ArrayList<E> v = (ArrayList<E>) super.clone();
356 >            ArrayList<?> v = (ArrayList<?>) super.clone();
357              v.elementData = Arrays.copyOf(elementData, size);
358              v.modCount = 0;
359              return v;
360          } catch (CloneNotSupportedException e) {
361              // this shouldn't happen, since we are Cloneable
362 <            throw new InternalError();
362 >            throw new InternalError(e);
363          }
364      }
365  
# Line 307 | Line 392 | public class ArrayList<E> extends Abstra
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 <     * <tt>null</tt>.  (This is useful in determining the length of the
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       *
# Line 338 | Line 423 | public class ArrayList<E> extends Abstra
423          return (E) elementData[index];
424      }
425  
426 +    @SuppressWarnings("unchecked")
427 +    static <E> E elementAt(Object[] es, int index) {
428 +        return (E) es[index];
429 +    }
430 +
431      /**
432       * Returns the element at the specified position in this list.
433       *
# Line 346 | Line 436 | public class ArrayList<E> extends Abstra
436       * @throws IndexOutOfBoundsException {@inheritDoc}
437       */
438      public E get(int index) {
439 <        rangeCheck(index);
350 <
439 >        Objects.checkIndex(index, size);
440          return elementData(index);
441      }
442  
# Line 361 | Line 450 | public class ArrayList<E> extends Abstra
450       * @throws IndexOutOfBoundsException {@inheritDoc}
451       */
452      public E set(int index, E element) {
453 <        rangeCheck(index);
365 <
453 >        Objects.checkIndex(index, size);
454          E oldValue = elementData(index);
455          elementData[index] = element;
456          return oldValue;
457      }
458  
459      /**
460 +     * This helper method split out from add(E) to keep method
461 +     * bytecode size under 35 (the -XX:MaxInlineSize default value),
462 +     * which helps when add(E) is called in a C1-compiled loop.
463 +     */
464 +    private void add(E e, Object[] elementData, int s) {
465 +        if (s == elementData.length)
466 +            elementData = grow();
467 +        elementData[s] = e;
468 +        size = s + 1;
469 +    }
470 +
471 +    /**
472       * Appends the specified element to the end of this list.
473       *
474       * @param e element to be appended to this list
475 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
475 >     * @return {@code true} (as specified by {@link Collection#add})
476       */
477      public boolean add(E e) {
478 <        ensureCapacity(size + 1);  // Increments modCount!!
479 <        elementData[size++] = e;
478 >        modCount++;
479 >        add(e, elementData, size);
480          return true;
481      }
482  
# Line 391 | Line 491 | public class ArrayList<E> extends Abstra
491       */
492      public void add(int index, E element) {
493          rangeCheckForAdd(index);
494 <
495 <        ensureCapacity(size+1);  // Increments modCount!!
496 <        System.arraycopy(elementData, index, elementData, index + 1,
497 <                         size - index);
494 >        modCount++;
495 >        final int s;
496 >        Object[] elementData;
497 >        if ((s = size) == (elementData = this.elementData).length)
498 >            elementData = grow();
499 >        System.arraycopy(elementData, index,
500 >                         elementData, index + 1,
501 >                         s - index);
502          elementData[index] = element;
503 <        size++;
503 >        size = s + 1;
504 >        // checkInvariants();
505      }
506  
507      /**
# Line 409 | Line 514 | public class ArrayList<E> extends Abstra
514       * @throws IndexOutOfBoundsException {@inheritDoc}
515       */
516      public E remove(int index) {
517 <        rangeCheck(index);
517 >        Objects.checkIndex(index, size);
518 >        final Object[] es = elementData;
519  
520 <        modCount++;
521 <        E oldValue = elementData(index);
416 <
417 <        int numMoved = size - index - 1;
418 <        if (numMoved > 0)
419 <            System.arraycopy(elementData, index+1, elementData, index,
420 <                             numMoved);
421 <        elementData[--size] = null; // Let gc do its work
520 >        @SuppressWarnings("unchecked") E oldValue = (E) es[index];
521 >        fastRemove(es, index);
522  
523 +        // checkInvariants();
524          return oldValue;
525      }
526  
# Line 427 | Line 528 | public class ArrayList<E> extends Abstra
528       * Removes the first occurrence of the specified element from this list,
529       * if it is present.  If the list does not contain the element, it is
530       * unchanged.  More formally, removes the element with the lowest index
531 <     * <tt>i</tt> such that
532 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
533 <     * (if such an element exists).  Returns <tt>true</tt> if this list
531 >     * {@code i} such that
532 >     * {@code Objects.equals(o, get(i))}
533 >     * (if such an element exists).  Returns {@code true} if this list
534       * contained the specified element (or equivalently, if this list
535       * changed as a result of the call).
536       *
537       * @param o element to be removed from this list, if present
538 <     * @return <tt>true</tt> if this list contained the specified element
538 >     * @return {@code true} if this list contained the specified element
539       */
540      public boolean remove(Object o) {
541 <        if (o == null) {
542 <            for (int index = 0; index < size; index++)
543 <                if (elementData[index] == null) {
544 <                    fastRemove(index);
545 <                    return true;
546 <                }
547 <        } else {
548 <            for (int index = 0; index < size; index++)
549 <                if (o.equals(elementData[index])) {
550 <                    fastRemove(index);
551 <                    return true;
552 <                }
541 >        final Object[] es = elementData;
542 >        final int size = this.size;
543 >        int i = 0;
544 >        found: {
545 >            if (o == null) {
546 >                for (; i < size; i++)
547 >                    if (es[i] == null)
548 >                        break found;
549 >            } else {
550 >                for (; i < size; i++)
551 >                    if (o.equals(es[i]))
552 >                        break found;
553 >            }
554 >            return false;
555          }
556 <        return false;
556 >        fastRemove(es, i);
557 >        return true;
558      }
559  
560 <    /*
560 >    /**
561       * Private remove method that skips bounds checking and does not
562       * return the value removed.
563       */
564 <    private void fastRemove(int index) {
564 >    private void fastRemove(Object[] es, int i) {
565          modCount++;
566 <        int numMoved = size - index - 1;
567 <        if (numMoved > 0)
568 <            System.arraycopy(elementData, index+1, elementData, index,
569 <                             numMoved);
466 <        elementData[--size] = null; // Let gc do its work
566 >        final int newSize;
567 >        if ((newSize = size - 1) > i)
568 >            System.arraycopy(es, i + 1, es, i, newSize - i);
569 >        es[size = newSize] = null;
570      }
571  
572      /**
# Line 472 | Line 575 | public class ArrayList<E> extends Abstra
575       */
576      public void clear() {
577          modCount++;
578 <
579 <        // Let gc do its work
580 <        for (int i = 0; i < size; i++)
478 <            elementData[i] = null;
479 <
480 <        size = 0;
578 >        final Object[] es = elementData;
579 >        for (int to = size, i = size = 0; i < to; i++)
580 >            es[i] = null;
581      }
582  
583      /**
# Line 490 | Line 590 | public class ArrayList<E> extends Abstra
590       * list is nonempty.)
591       *
592       * @param c collection containing elements to be added to this list
593 <     * @return <tt>true</tt> if this list changed as a result of the call
593 >     * @return {@code true} if this list changed as a result of the call
594       * @throws NullPointerException if the specified collection is null
595       */
596      public boolean addAll(Collection<? extends E> c) {
597          Object[] a = c.toArray();
598 +        modCount++;
599          int numNew = a.length;
600 <        ensureCapacity(size + numNew);  // Increments modCount
601 <        System.arraycopy(a, 0, elementData, size, numNew);
602 <        size += numNew;
603 <        return numNew != 0;
600 >        if (numNew == 0)
601 >            return false;
602 >        Object[] elementData;
603 >        final int s;
604 >        if (numNew > (elementData = this.elementData).length - (s = size))
605 >            elementData = grow(s + numNew);
606 >        System.arraycopy(a, 0, elementData, s, numNew);
607 >        size = s + numNew;
608 >        // checkInvariants();
609 >        return true;
610      }
611  
612      /**
# Line 513 | Line 620 | public class ArrayList<E> extends Abstra
620       * @param index index at which to insert the first element from the
621       *              specified collection
622       * @param c collection containing elements to be added to this list
623 <     * @return <tt>true</tt> if this list changed as a result of the call
623 >     * @return {@code true} if this list changed as a result of the call
624       * @throws IndexOutOfBoundsException {@inheritDoc}
625       * @throws NullPointerException if the specified collection is null
626       */
# Line 521 | Line 628 | public class ArrayList<E> extends Abstra
628          rangeCheckForAdd(index);
629  
630          Object[] a = c.toArray();
631 +        modCount++;
632          int numNew = a.length;
633 <        ensureCapacity(size + numNew);  // Increments modCount
633 >        if (numNew == 0)
634 >            return false;
635 >        Object[] elementData;
636 >        final int s;
637 >        if (numNew > (elementData = this.elementData).length - (s = size))
638 >            elementData = grow(s + numNew);
639  
640 <        int numMoved = size - index;
640 >        int numMoved = s - index;
641          if (numMoved > 0)
642 <            System.arraycopy(elementData, index, elementData, index + numNew,
642 >            System.arraycopy(elementData, index,
643 >                             elementData, index + numNew,
644                               numMoved);
531
645          System.arraycopy(a, 0, elementData, index, numNew);
646 <        size += numNew;
647 <        return numNew != 0;
646 >        size = s + numNew;
647 >        // checkInvariants();
648 >        return true;
649      }
650  
651      /**
# Line 544 | Line 658 | public class ArrayList<E> extends Abstra
658       * @throws IndexOutOfBoundsException if {@code fromIndex} or
659       *         {@code toIndex} is out of range
660       *         ({@code fromIndex < 0 ||
547     *          fromIndex >= size() ||
661       *          toIndex > size() ||
662       *          toIndex < fromIndex})
663       */
664      protected void removeRange(int fromIndex, int toIndex) {
665 +        if (fromIndex > toIndex) {
666 +            throw new IndexOutOfBoundsException(
667 +                    outOfBoundsMsg(fromIndex, toIndex));
668 +        }
669          modCount++;
670 <        int numMoved = size - toIndex;
671 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
555 <                         numMoved);
556 <
557 <        // Let gc do its work
558 <        int newSize = size - (toIndex-fromIndex);
559 <        while (size != newSize)
560 <            elementData[--size] = null;
670 >        shiftTailOverGap(elementData, fromIndex, toIndex);
671 >        // checkInvariants();
672      }
673  
674 <    /**
675 <     * Checks if the given index is in range.  If not, throws an appropriate
676 <     * runtime exception.  This method does *not* check if the index is
677 <     * negative: It is always used immediately prior to an array access,
678 <     * which throws an ArrayIndexOutOfBoundsException if index is negative.
568 <     */
569 <    private void rangeCheck(int index) {
570 <        if (index >= size)
571 <            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
674 >    /** Erases the gap from lo to hi, by sliding down following elements. */
675 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
676 >        System.arraycopy(es, hi, es, lo, size - hi);
677 >        for (int to = size, i = (size -= hi - lo); i < to; i++)
678 >            es[i] = null;
679      }
680  
681      /**
# Line 589 | Line 696 | public class ArrayList<E> extends Abstra
696      }
697  
698      /**
699 +     * A version used in checking (fromIndex > toIndex) condition
700 +     */
701 +    private static String outOfBoundsMsg(int fromIndex, int toIndex) {
702 +        return "From Index: " + fromIndex + " > To Index: " + toIndex;
703 +    }
704 +
705 +    /**
706       * Removes from this list all of its elements that are contained in the
707       * specified collection.
708       *
709       * @param c collection containing elements to be removed from this list
710       * @return {@code true} if this list changed as a result of the call
711       * @throws ClassCastException if the class of an element of this list
712 <     *         is incompatible with the specified collection (optional)
712 >     *         is incompatible with the specified collection
713 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
714       * @throws NullPointerException if this list contains a null element and the
715 <     *         specified collection does not permit null elements (optional),
715 >     *         specified collection does not permit null elements
716 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
717       *         or if the specified collection is null
718       * @see Collection#contains(Object)
719       */
720      public boolean removeAll(Collection<?> c) {
721 <        return batchRemove(c, false);
721 >        return batchRemove(c, false, 0, size);
722      }
723  
724      /**
# Line 613 | Line 729 | public class ArrayList<E> extends Abstra
729       * @param c collection containing elements to be retained in this list
730       * @return {@code true} if this list changed as a result of the call
731       * @throws ClassCastException if the class of an element of this list
732 <     *         is incompatible with the specified collection (optional)
732 >     *         is incompatible with the specified collection
733 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
734       * @throws NullPointerException if this list contains a null element and the
735 <     *         specified collection does not permit null elements (optional),
735 >     *         specified collection does not permit null elements
736 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
737       *         or if the specified collection is null
738       * @see Collection#contains(Object)
739       */
740      public boolean retainAll(Collection<?> c) {
741 <        return batchRemove(c, true);
741 >        return batchRemove(c, true, 0, size);
742      }
743  
744 <    private boolean batchRemove(Collection<?> c, boolean complement) {
745 <        final Object[] elementData = this.elementData;
746 <        int r = 0, w = 0;
747 <        boolean modified = false;
748 <        try {
749 <            for (; r < size; r++)
750 <                if (c.contains(elementData[r]) == complement)
751 <                    elementData[w++] = elementData[r];
752 <        } finally {
753 <            // Preserve behavioral compatibility with AbstractCollection,
754 <            // even if c.contains() throws.
755 <            if (r != size) {
756 <                System.arraycopy(elementData, r,
757 <                                 elementData, w,
758 <                                 size - r);
759 <                w += size - r;
760 <            }
761 <            if (w != size) {
762 <                for (int i = w; i < size; i++)
763 <                    elementData[i] = null;
764 <                modCount += size - w;
765 <                size = w;
766 <                modified = true;
744 >    boolean batchRemove(Collection<?> c, boolean complement,
745 >                        final int from, final int end) {
746 >        Objects.requireNonNull(c);
747 >        final Object[] es = elementData;
748 >        final boolean modified;
749 >        int r;
750 >        // Optimize for initial run of survivors
751 >        for (r = from; r < end && c.contains(es[r]) == complement; r++)
752 >            ;
753 >        if (modified = (r < end)) {
754 >            int w = r++;
755 >            try {
756 >                for (Object e; r < end; r++)
757 >                    if (c.contains(e = es[r]) == complement)
758 >                        es[w++] = e;
759 >            } catch (Throwable ex) {
760 >                // Preserve behavioral compatibility with AbstractCollection,
761 >                // even if c.contains() throws.
762 >                System.arraycopy(es, r, es, w, end - r);
763 >                w += end - r;
764 >                throw ex;
765 >            } finally {
766 >                modCount += end - w;
767 >                shiftTailOverGap(es, w, end);
768              }
769          }
770 +        // checkInvariants();
771          return modified;
772      }
773  
774      /**
775 <     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
776 <     * is, serialize it).
775 >     * Saves the state of the {@code ArrayList} instance to a stream
776 >     * (that is, serializes it).
777       *
778 <     * @serialData The length of the array backing the <tt>ArrayList</tt>
778 >     * @param s the stream
779 >     * @throws java.io.IOException if an I/O error occurs
780 >     * @serialData The length of the array backing the {@code ArrayList}
781       *             instance is emitted (int), followed by all of its elements
782 <     *             (each an <tt>Object</tt>) in the proper order.
782 >     *             (each an {@code Object}) in the proper order.
783       */
784      private void writeObject(java.io.ObjectOutputStream s)
785 <        throws java.io.IOException{
785 >        throws java.io.IOException {
786          // Write out element count, and any hidden stuff
787          int expectedModCount = modCount;
788          s.defaultWriteObject();
789  
790 <        // Write out array length
791 <        s.writeInt(elementData.length);
790 >        // Write out size as capacity for behavioural compatibility with clone()
791 >        s.writeInt(size);
792  
793          // Write out all elements in the proper order.
794 <        for (int i=0; i<size; i++)
794 >        for (int i=0; i<size; i++) {
795              s.writeObject(elementData[i]);
796 +        }
797  
798          if (modCount != expectedModCount) {
799              throw new ConcurrentModificationException();
800          }
678
801      }
802  
803      /**
804 <     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
805 <     * deserialize it).
804 >     * Reconstitutes the {@code ArrayList} instance from a stream (that is,
805 >     * deserializes it).
806 >     * @param s the stream
807 >     * @throws ClassNotFoundException if the class of a serialized object
808 >     *         could not be found
809 >     * @throws java.io.IOException if an I/O error occurs
810       */
811      private void readObject(java.io.ObjectInputStream s)
812          throws java.io.IOException, ClassNotFoundException {
813 +
814          // Read in size, and any hidden stuff
815          s.defaultReadObject();
816  
817 <        // Read in array length and allocate array
818 <        int arrayLength = s.readInt();
819 <        Object[] a = elementData = new Object[arrayLength];
820 <
821 <        // Read in all elements in the proper order.
822 <        for (int i=0; i<size; i++)
823 <            a[i] = s.readObject();
817 >        // Read in capacity
818 >        s.readInt(); // ignored
819 >
820 >        if (size > 0) {
821 >            // like clone(), allocate array based upon size not capacity
822 >            Object[] elements = new Object[size];
823 >
824 >            // Read in all elements in the proper order.
825 >            for (int i = 0; i < size; i++) {
826 >                elements[i] = s.readObject();
827 >            }
828 >
829 >            elementData = elements;
830 >        } else if (size == 0) {
831 >            elementData = EMPTY_ELEMENTDATA;
832 >        } else {
833 >            throw new java.io.InvalidObjectException("Invalid size: " + size);
834 >        }
835      }
836  
837      /**
# Line 709 | Line 847 | public class ArrayList<E> extends Abstra
847       * @throws IndexOutOfBoundsException {@inheritDoc}
848       */
849      public ListIterator<E> listIterator(int index) {
850 <        if (index < 0 || index > size)
713 <            throw new IndexOutOfBoundsException("Index: "+index);
850 >        rangeCheckForAdd(index);
851          return new ListItr(index);
852      }
853  
# Line 745 | Line 882 | public class ArrayList<E> extends Abstra
882          int lastRet = -1; // index of last element returned; -1 if no such
883          int expectedModCount = modCount;
884  
885 +        // prevent creating a synthetic constructor
886 +        Itr() {}
887 +
888          public boolean hasNext() {
889              return cursor != size;
890          }
# Line 777 | Line 917 | public class ArrayList<E> extends Abstra
917              }
918          }
919  
920 +        @Override
921 +        public void forEachRemaining(Consumer<? super E> action) {
922 +            Objects.requireNonNull(action);
923 +            final int size = ArrayList.this.size;
924 +            int i = cursor;
925 +            if (i < size) {
926 +                final Object[] es = elementData;
927 +                if (i >= es.length)
928 +                    throw new ConcurrentModificationException();
929 +                for (; i < size && modCount == expectedModCount; i++)
930 +                    action.accept(elementAt(es, i));
931 +                // update once at end to reduce heap write traffic
932 +                cursor = i;
933 +                lastRet = i - 1;
934 +                checkForComodification();
935 +            }
936 +        }
937 +
938          final void checkForComodification() {
939              if (modCount != expectedModCount)
940                  throw new ConcurrentModificationException();
# Line 875 | Line 1033 | public class ArrayList<E> extends Abstra
1033       */
1034      public List<E> subList(int fromIndex, int toIndex) {
1035          subListRangeCheck(fromIndex, toIndex, size);
1036 <        return new SubList(this, 0, fromIndex, toIndex);
1036 >        return new SubList<>(this, fromIndex, toIndex);
1037      }
1038  
1039 <    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
1040 <        if (fromIndex < 0)
1041 <            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
884 <        if (toIndex > size)
885 <            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
886 <        if (fromIndex > toIndex)
887 <            throw new IllegalArgumentException("fromIndex(" + fromIndex +
888 <                                               ") > toIndex(" + toIndex + ")");
889 <    }
890 <
891 <    private class SubList extends AbstractList<E> implements RandomAccess {
892 <        private final AbstractList<E> parent;
893 <        private final int parentOffset;
1039 >    private static class SubList<E> extends AbstractList<E> implements RandomAccess {
1040 >        private final ArrayList<E> root;
1041 >        private final SubList<E> parent;
1042          private final int offset;
1043 <        int size;
1043 >        private int size;
1044 >
1045 >        /**
1046 >         * Constructs a sublist of an arbitrary ArrayList.
1047 >         */
1048 >        public SubList(ArrayList<E> root, int fromIndex, int toIndex) {
1049 >            this.root = root;
1050 >            this.parent = null;
1051 >            this.offset = fromIndex;
1052 >            this.size = toIndex - fromIndex;
1053 >            this.modCount = root.modCount;
1054 >        }
1055  
1056 <        SubList(AbstractList<E> parent,
1057 <                int offset, int fromIndex, int toIndex) {
1056 >        /**
1057 >         * Constructs a sublist of another SubList.
1058 >         */
1059 >        private SubList(SubList<E> parent, int fromIndex, int toIndex) {
1060 >            this.root = parent.root;
1061              this.parent = parent;
1062 <            this.parentOffset = fromIndex;
901 <            this.offset = offset + fromIndex;
1062 >            this.offset = parent.offset + fromIndex;
1063              this.size = toIndex - fromIndex;
1064 <            this.modCount = ArrayList.this.modCount;
1064 >            this.modCount = root.modCount;
1065          }
1066  
1067 <        public E set(int index, E e) {
1068 <            rangeCheck(index);
1067 >        public E set(int index, E element) {
1068 >            Objects.checkIndex(index, size);
1069              checkForComodification();
1070 <            E oldValue = ArrayList.this.elementData(offset + index);
1071 <            ArrayList.this.elementData[offset + index] = e;
1070 >            E oldValue = root.elementData(offset + index);
1071 >            root.elementData[offset + index] = element;
1072              return oldValue;
1073          }
1074  
1075          public E get(int index) {
1076 <            rangeCheck(index);
1076 >            Objects.checkIndex(index, size);
1077              checkForComodification();
1078 <            return ArrayList.this.elementData(offset + index);
1078 >            return root.elementData(offset + index);
1079          }
1080  
1081          public int size() {
1082              checkForComodification();
1083 <            return this.size;
1083 >            return size;
1084          }
1085  
1086 <        public void add(int index, E e) {
1086 >        public void add(int index, E element) {
1087              rangeCheckForAdd(index);
1088              checkForComodification();
1089 <            parent.add(parentOffset + index, e);
1090 <            this.modCount = parent.modCount;
930 <            this.size++;
1089 >            root.add(offset + index, element);
1090 >            updateSizeAndModCount(1);
1091          }
1092  
1093          public E remove(int index) {
1094 <            rangeCheck(index);
1094 >            Objects.checkIndex(index, size);
1095              checkForComodification();
1096 <            E result = parent.remove(parentOffset + index);
1097 <            this.modCount = parent.modCount;
938 <            this.size--;
1096 >            E result = root.remove(offset + index);
1097 >            updateSizeAndModCount(-1);
1098              return result;
1099          }
1100  
1101          protected void removeRange(int fromIndex, int toIndex) {
1102              checkForComodification();
1103 <            parent.removeRange(parentOffset + fromIndex,
1104 <                               parentOffset + toIndex);
946 <            this.modCount = parent.modCount;
947 <            this.size -= toIndex - fromIndex;
1103 >            root.removeRange(offset + fromIndex, offset + toIndex);
1104 >            updateSizeAndModCount(fromIndex - toIndex);
1105          }
1106  
1107          public boolean addAll(Collection<? extends E> c) {
# Line 956 | Line 1113 | public class ArrayList<E> extends Abstra
1113              int cSize = c.size();
1114              if (cSize==0)
1115                  return false;
959
1116              checkForComodification();
1117 <            parent.addAll(parentOffset + index, c);
1118 <            this.modCount = parent.modCount;
963 <            this.size += cSize;
1117 >            root.addAll(offset + index, c);
1118 >            updateSizeAndModCount(cSize);
1119              return true;
1120          }
1121  
1122 +        public boolean removeAll(Collection<?> c) {
1123 +            return batchRemove(c, false);
1124 +        }
1125 +
1126 +        public boolean retainAll(Collection<?> c) {
1127 +            return batchRemove(c, true);
1128 +        }
1129 +
1130 +        private boolean batchRemove(Collection<?> c, boolean complement) {
1131 +            checkForComodification();
1132 +            int oldSize = root.size;
1133 +            boolean modified =
1134 +                root.batchRemove(c, complement, offset, offset + size);
1135 +            if (modified)
1136 +                updateSizeAndModCount(root.size - oldSize);
1137 +            return modified;
1138 +        }
1139 +
1140 +        public boolean removeIf(Predicate<? super E> filter) {
1141 +            checkForComodification();
1142 +            int oldSize = root.size;
1143 +            boolean modified = root.removeIf(filter, offset, offset + size);
1144 +            if (modified)
1145 +                updateSizeAndModCount(root.size - oldSize);
1146 +            return modified;
1147 +        }
1148 +
1149          public Iterator<E> iterator() {
1150              return listIterator();
1151          }
1152  
1153 <        public ListIterator<E> listIterator(final int index) {
1153 >        public ListIterator<E> listIterator(int index) {
1154              checkForComodification();
1155              rangeCheckForAdd(index);
974            final int offset = this.offset;
1156  
1157              return new ListIterator<E>() {
1158                  int cursor = index;
1159                  int lastRet = -1;
1160 <                int expectedModCount = ArrayList.this.modCount;
1160 >                int expectedModCount = root.modCount;
1161  
1162                  public boolean hasNext() {
1163                      return cursor != SubList.this.size;
# Line 988 | Line 1169 | public class ArrayList<E> extends Abstra
1169                      int i = cursor;
1170                      if (i >= SubList.this.size)
1171                          throw new NoSuchElementException();
1172 <                    Object[] elementData = ArrayList.this.elementData;
1172 >                    Object[] elementData = root.elementData;
1173                      if (offset + i >= elementData.length)
1174                          throw new ConcurrentModificationException();
1175                      cursor = i + 1;
# Line 1005 | Line 1186 | public class ArrayList<E> extends Abstra
1186                      int i = cursor - 1;
1187                      if (i < 0)
1188                          throw new NoSuchElementException();
1189 <                    Object[] elementData = ArrayList.this.elementData;
1189 >                    Object[] elementData = root.elementData;
1190                      if (offset + i >= elementData.length)
1191                          throw new ConcurrentModificationException();
1192                      cursor = i;
1193                      return (E) elementData[offset + (lastRet = i)];
1194                  }
1195  
1196 +                public void forEachRemaining(Consumer<? super E> action) {
1197 +                    Objects.requireNonNull(action);
1198 +                    final int size = SubList.this.size;
1199 +                    int i = cursor;
1200 +                    if (i < size) {
1201 +                        final Object[] es = root.elementData;
1202 +                        if (offset + i >= es.length)
1203 +                            throw new ConcurrentModificationException();
1204 +                        for (; i < size && modCount == expectedModCount; i++)
1205 +                            action.accept(elementAt(es, offset + i));
1206 +                        // update once at end to reduce heap write traffic
1207 +                        cursor = i;
1208 +                        lastRet = i - 1;
1209 +                        checkForComodification();
1210 +                    }
1211 +                }
1212 +
1213                  public int nextIndex() {
1214                      return cursor;
1215                  }
# Line 1029 | Line 1227 | public class ArrayList<E> extends Abstra
1227                          SubList.this.remove(lastRet);
1228                          cursor = lastRet;
1229                          lastRet = -1;
1230 <                        expectedModCount = ArrayList.this.modCount;
1230 >                        expectedModCount = root.modCount;
1231                      } catch (IndexOutOfBoundsException ex) {
1232                          throw new ConcurrentModificationException();
1233                      }
# Line 1041 | Line 1239 | public class ArrayList<E> extends Abstra
1239                      checkForComodification();
1240  
1241                      try {
1242 <                        ArrayList.this.set(offset + lastRet, e);
1242 >                        root.set(offset + lastRet, e);
1243                      } catch (IndexOutOfBoundsException ex) {
1244                          throw new ConcurrentModificationException();
1245                      }
# Line 1055 | Line 1253 | public class ArrayList<E> extends Abstra
1253                          SubList.this.add(i, e);
1254                          cursor = i + 1;
1255                          lastRet = -1;
1256 <                        expectedModCount = ArrayList.this.modCount;
1256 >                        expectedModCount = root.modCount;
1257                      } catch (IndexOutOfBoundsException ex) {
1258                          throw new ConcurrentModificationException();
1259                      }
1260                  }
1261  
1262                  final void checkForComodification() {
1263 <                    if (expectedModCount != ArrayList.this.modCount)
1263 >                    if (root.modCount != expectedModCount)
1264                          throw new ConcurrentModificationException();
1265                  }
1266              };
# Line 1070 | Line 1268 | public class ArrayList<E> extends Abstra
1268  
1269          public List<E> subList(int fromIndex, int toIndex) {
1270              subListRangeCheck(fromIndex, toIndex, size);
1271 <            return new SubList(this, offset, fromIndex, toIndex);
1074 <        }
1075 <
1076 <        private void rangeCheck(int index) {
1077 <            if (index < 0 || index >= this.size)
1078 <                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1271 >            return new SubList<>(this, fromIndex, toIndex);
1272          }
1273  
1274          private void rangeCheckForAdd(int index) {
# Line 1088 | Line 1281 | public class ArrayList<E> extends Abstra
1281          }
1282  
1283          private void checkForComodification() {
1284 <            if (ArrayList.this.modCount != this.modCount)
1284 >            if (root.modCount != modCount)
1285                  throw new ConcurrentModificationException();
1286          }
1287 +
1288 +        private void updateSizeAndModCount(int sizeChange) {
1289 +            SubList<E> slist = this;
1290 +            do {
1291 +                slist.size += sizeChange;
1292 +                slist.modCount = root.modCount;
1293 +                slist = slist.parent;
1294 +            } while (slist != null);
1295 +        }
1296 +
1297 +        public Spliterator<E> spliterator() {
1298 +            checkForComodification();
1299 +
1300 +            // ArrayListSpliterator not used here due to late-binding
1301 +            return new Spliterator<E>() {
1302 +                private int index = offset; // current index, modified on advance/split
1303 +                private int fence = -1; // -1 until used; then one past last index
1304 +                private int expectedModCount; // initialized when fence set
1305 +
1306 +                private int getFence() { // initialize fence to size on first use
1307 +                    int hi; // (a specialized variant appears in method forEach)
1308 +                    if ((hi = fence) < 0) {
1309 +                        expectedModCount = modCount;
1310 +                        hi = fence = offset + size;
1311 +                    }
1312 +                    return hi;
1313 +                }
1314 +
1315 +                public ArrayList<E>.ArrayListSpliterator trySplit() {
1316 +                    int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1317 +                    // ArrayListSpliterator can be used here as the source is already bound
1318 +                    return (lo >= mid) ? null : // divide range in half unless too small
1319 +                        root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
1320 +                }
1321 +
1322 +                public boolean tryAdvance(Consumer<? super E> action) {
1323 +                    Objects.requireNonNull(action);
1324 +                    int hi = getFence(), i = index;
1325 +                    if (i < hi) {
1326 +                        index = i + 1;
1327 +                        @SuppressWarnings("unchecked") E e = (E)root.elementData[i];
1328 +                        action.accept(e);
1329 +                        if (root.modCount != expectedModCount)
1330 +                            throw new ConcurrentModificationException();
1331 +                        return true;
1332 +                    }
1333 +                    return false;
1334 +                }
1335 +
1336 +                public void forEachRemaining(Consumer<? super E> action) {
1337 +                    Objects.requireNonNull(action);
1338 +                    int i, hi, mc; // hoist accesses and checks from loop
1339 +                    ArrayList<E> lst = root;
1340 +                    Object[] a;
1341 +                    if ((a = lst.elementData) != null) {
1342 +                        if ((hi = fence) < 0) {
1343 +                            mc = modCount;
1344 +                            hi = offset + size;
1345 +                        }
1346 +                        else
1347 +                            mc = expectedModCount;
1348 +                        if ((i = index) >= 0 && (index = hi) <= a.length) {
1349 +                            for (; i < hi; ++i) {
1350 +                                @SuppressWarnings("unchecked") E e = (E) a[i];
1351 +                                action.accept(e);
1352 +                            }
1353 +                            if (lst.modCount == mc)
1354 +                                return;
1355 +                        }
1356 +                    }
1357 +                    throw new ConcurrentModificationException();
1358 +                }
1359 +
1360 +                public long estimateSize() {
1361 +                    return getFence() - index;
1362 +                }
1363 +
1364 +                public int characteristics() {
1365 +                    return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1366 +                }
1367 +            };
1368 +        }
1369 +    }
1370 +
1371 +    /**
1372 +     * @throws NullPointerException {@inheritDoc}
1373 +     */
1374 +    @Override
1375 +    public void forEach(Consumer<? super E> action) {
1376 +        Objects.requireNonNull(action);
1377 +        final int expectedModCount = modCount;
1378 +        final Object[] es = elementData;
1379 +        final int size = this.size;
1380 +        for (int i = 0; modCount == expectedModCount && i < size; i++)
1381 +            action.accept(elementAt(es, i));
1382 +        if (modCount != expectedModCount)
1383 +            throw new ConcurrentModificationException();
1384 +    }
1385 +
1386 +    /**
1387 +     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1388 +     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1389 +     * list.
1390 +     *
1391 +     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1392 +     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1393 +     * Overriding implementations should document the reporting of additional
1394 +     * characteristic values.
1395 +     *
1396 +     * @return a {@code Spliterator} over the elements in this list
1397 +     * @since 1.8
1398 +     */
1399 +    @Override
1400 +    public Spliterator<E> spliterator() {
1401 +        return new ArrayListSpliterator(0, -1, 0);
1402 +    }
1403 +
1404 +    /** Index-based split-by-two, lazily initialized Spliterator */
1405 +    final class ArrayListSpliterator implements Spliterator<E> {
1406 +
1407 +        /*
1408 +         * If ArrayLists were immutable, or structurally immutable (no
1409 +         * adds, removes, etc), we could implement their spliterators
1410 +         * with Arrays.spliterator. Instead we detect as much
1411 +         * interference during traversal as practical without
1412 +         * sacrificing much performance. We rely primarily on
1413 +         * modCounts. These are not guaranteed to detect concurrency
1414 +         * violations, and are sometimes overly conservative about
1415 +         * within-thread interference, but detect enough problems to
1416 +         * be worthwhile in practice. To carry this out, we (1) lazily
1417 +         * initialize fence and expectedModCount until the latest
1418 +         * point that we need to commit to the state we are checking
1419 +         * against; thus improving precision.  (This doesn't apply to
1420 +         * SubLists, that create spliterators with current non-lazy
1421 +         * values).  (2) We perform only a single
1422 +         * ConcurrentModificationException check at the end of forEach
1423 +         * (the most performance-sensitive method). When using forEach
1424 +         * (as opposed to iterators), we can normally only detect
1425 +         * interference after actions, not before. Further
1426 +         * CME-triggering checks apply to all other possible
1427 +         * violations of assumptions for example null or too-small
1428 +         * elementData array given its size(), that could only have
1429 +         * occurred due to interference.  This allows the inner loop
1430 +         * of forEach to run without any further checks, and
1431 +         * simplifies lambda-resolution. While this does entail a
1432 +         * number of checks, note that in the common case of
1433 +         * list.stream().forEach(a), no checks or other computation
1434 +         * occur anywhere other than inside forEach itself.  The other
1435 +         * less-often-used methods cannot take advantage of most of
1436 +         * these streamlinings.
1437 +         */
1438 +
1439 +        private int index; // current index, modified on advance/split
1440 +        private int fence; // -1 until used; then one past last index
1441 +        private int expectedModCount; // initialized when fence set
1442 +
1443 +        /** Creates new spliterator covering the given range. */
1444 +        ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1445 +            this.index = origin;
1446 +            this.fence = fence;
1447 +            this.expectedModCount = expectedModCount;
1448 +        }
1449 +
1450 +        private int getFence() { // initialize fence to size on first use
1451 +            int hi; // (a specialized variant appears in method forEach)
1452 +            if ((hi = fence) < 0) {
1453 +                expectedModCount = modCount;
1454 +                hi = fence = size;
1455 +            }
1456 +            return hi;
1457 +        }
1458 +
1459 +        public ArrayListSpliterator trySplit() {
1460 +            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1461 +            return (lo >= mid) ? null : // divide range in half unless too small
1462 +                new ArrayListSpliterator(lo, index = mid, expectedModCount);
1463 +        }
1464 +
1465 +        public boolean tryAdvance(Consumer<? super E> action) {
1466 +            if (action == null)
1467 +                throw new NullPointerException();
1468 +            int hi = getFence(), i = index;
1469 +            if (i < hi) {
1470 +                index = i + 1;
1471 +                @SuppressWarnings("unchecked") E e = (E)elementData[i];
1472 +                action.accept(e);
1473 +                if (modCount != expectedModCount)
1474 +                    throw new ConcurrentModificationException();
1475 +                return true;
1476 +            }
1477 +            return false;
1478 +        }
1479 +
1480 +        public void forEachRemaining(Consumer<? super E> action) {
1481 +            int i, hi, mc; // hoist accesses and checks from loop
1482 +            Object[] a;
1483 +            if (action == null)
1484 +                throw new NullPointerException();
1485 +            if ((a = elementData) != null) {
1486 +                if ((hi = fence) < 0) {
1487 +                    mc = modCount;
1488 +                    hi = size;
1489 +                }
1490 +                else
1491 +                    mc = expectedModCount;
1492 +                if ((i = index) >= 0 && (index = hi) <= a.length) {
1493 +                    for (; i < hi; ++i) {
1494 +                        @SuppressWarnings("unchecked") E e = (E) a[i];
1495 +                        action.accept(e);
1496 +                    }
1497 +                    if (modCount == mc)
1498 +                        return;
1499 +                }
1500 +            }
1501 +            throw new ConcurrentModificationException();
1502 +        }
1503 +
1504 +        public long estimateSize() {
1505 +            return getFence() - index;
1506 +        }
1507 +
1508 +        public int characteristics() {
1509 +            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1510 +        }
1511 +    }
1512 +
1513 +    // A tiny bit set implementation
1514 +
1515 +    private static long[] nBits(int n) {
1516 +        return new long[((n - 1) >> 6) + 1];
1517 +    }
1518 +    private static void setBit(long[] bits, int i) {
1519 +        bits[i >> 6] |= 1L << i;
1520 +    }
1521 +    private static boolean isClear(long[] bits, int i) {
1522 +        return (bits[i >> 6] & (1L << i)) == 0;
1523 +    }
1524 +
1525 +    /**
1526 +     * @throws NullPointerException {@inheritDoc}
1527 +     */
1528 +    @Override
1529 +    public boolean removeIf(Predicate<? super E> filter) {
1530 +        return removeIf(filter, 0, size);
1531 +    }
1532 +
1533 +    /**
1534 +     * Removes all elements satisfying the given predicate, from index
1535 +     * i (inclusive) to index end (exclusive).
1536 +     */
1537 +    boolean removeIf(Predicate<? super E> filter, int i, final int end) {
1538 +        Objects.requireNonNull(filter);
1539 +        int expectedModCount = modCount;
1540 +        final Object[] es = elementData;
1541 +        // Optimize for initial run of survivors
1542 +        for (; i < end && !filter.test(elementAt(es, i)); i++)
1543 +            ;
1544 +        // Tolerate predicates that reentrantly access the collection for
1545 +        // read (but writers still get CME), so traverse once to find
1546 +        // elements to delete, a second pass to physically expunge.
1547 +        if (i < end) {
1548 +            final int beg = i;
1549 +            final long[] deathRow = nBits(end - beg);
1550 +            deathRow[0] = 1L;   // set bit 0
1551 +            for (i = beg + 1; i < end; i++)
1552 +                if (filter.test(elementAt(es, i)))
1553 +                    setBit(deathRow, i - beg);
1554 +            if (modCount != expectedModCount)
1555 +                throw new ConcurrentModificationException();
1556 +            expectedModCount++;
1557 +            modCount++;
1558 +            int w = beg;
1559 +            for (i = beg; i < end; i++)
1560 +                if (isClear(deathRow, i - beg))
1561 +                    es[w++] = es[i];
1562 +            shiftTailOverGap(es, w, end);
1563 +            // checkInvariants();
1564 +            return true;
1565 +        } else {
1566 +            if (modCount != expectedModCount)
1567 +                throw new ConcurrentModificationException();
1568 +            // checkInvariants();
1569 +            return false;
1570 +        }
1571 +    }
1572 +
1573 +    @Override
1574 +    public void replaceAll(UnaryOperator<E> operator) {
1575 +        Objects.requireNonNull(operator);
1576 +        final int expectedModCount = modCount;
1577 +        final Object[] es = elementData;
1578 +        final int size = this.size;
1579 +        for (int i = 0; modCount == expectedModCount && i < size; i++)
1580 +            es[i] = operator.apply(elementAt(es, i));
1581 +        if (modCount != expectedModCount)
1582 +            throw new ConcurrentModificationException();
1583 +        modCount++;
1584 +        // checkInvariants();
1585 +    }
1586 +
1587 +    @Override
1588 +    @SuppressWarnings("unchecked")
1589 +    public void sort(Comparator<? super E> c) {
1590 +        final int expectedModCount = modCount;
1591 +        Arrays.sort((E[]) elementData, 0, size, c);
1592 +        if (modCount != expectedModCount)
1593 +            throw new ConcurrentModificationException();
1594 +        modCount++;
1595 +        // checkInvariants();
1596 +    }
1597 +
1598 +    void checkInvariants() {
1599 +        // assert size >= 0;
1600 +        // assert size == elementData.length || elementData[size] == null;
1601      }
1602   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines