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.13 by dl, Mon Nov 28 23:53:32 2005 UTC vs.
Revision 1.70 by jsr166, Fri Jan 10 21:32:08 2020 UTC

# Line 1 | Line 1
1   /*
2 < * %W% %E%
2 > * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
3 > * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5 < * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
6 < * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
5 > * This code is free software; you can redistribute it and/or modify it
6 > * under the terms of the GNU General Public License version 2 only, as
7 > * published by the Free Software Foundation.  Oracle designates this
8 > * particular file as subject to the "Classpath" exception as provided
9 > * by Oracle in the LICENSE file that accompanied this code.
10 > *
11 > * This code is distributed in the hope that it will be useful, but WITHOUT
12 > * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 > * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 > * version 2 for more details (a copy is included in the LICENSE file that
15 > * accompanied this code).
16 > *
17 > * You should have received a copy of the GNU General Public License version
18 > * 2 along with this work; if not, write to the Free Software Foundation,
19 > * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 > *
21 > * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 > * or visit www.oracle.com if you need additional information or have any
23 > * questions.
24   */
25  
26   package java.util;
27 < import java.util.*; // for javadoc (till 6280605 is fixed)
27 >
28 > import java.util.function.Consumer;
29 > import java.util.function.Predicate;
30 > import java.util.function.UnaryOperator;
31 > // OPENJDK import jdk.internal.access.SharedSecrets;
32 > import jdk.internal.util.ArraysSupport;
33  
34   /**
35 < * Resizable-array implementation of the <tt>List</tt> interface.  Implements
35 > * Resizable-array implementation of the {@code List} interface.  Implements
36   * all optional list operations, and permits all elements, including
37 < * <tt>null</tt>.  In addition to implementing the <tt>List</tt> interface,
37 > * {@code null}.  In addition to implementing the {@code List} interface,
38   * this class provides methods to manipulate the size of the array that is
39   * used internally to store the list.  (This class is roughly equivalent to
40 < * <tt>Vector</tt>, except that it is unsynchronized.)<p>
40 > * {@code Vector}, except that it is unsynchronized.)
41   *
42 < * The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
43 < * <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
44 < * time.  The <tt>add</tt> operation runs in <i>amortized constant time</i>,
42 > * <p>The {@code size}, {@code isEmpty}, {@code get}, {@code set},
43 > * {@code iterator}, and {@code listIterator} operations run in constant
44 > * time.  The {@code add} operation runs in <i>amortized constant time</i>,
45   * that is, adding n elements requires O(n) time.  All of the other operations
46   * run in linear time (roughly speaking).  The constant factor is low compared
47 < * to that for the <tt>LinkedList</tt> implementation.<p>
47 > * to that for the {@code LinkedList} implementation.
48   *
49 < * Each <tt>ArrayList</tt> instance has a <i>capacity</i>.  The capacity is
49 > * <p>Each {@code ArrayList} instance has a <i>capacity</i>.  The capacity is
50   * the size of the array used to store the elements in the list.  It is always
51   * at least as large as the list size.  As elements are added to an ArrayList,
52   * its capacity grows automatically.  The details of the growth policy are not
53   * specified beyond the fact that adding an element has constant amortized
54 < * time cost.<p>
54 > * time cost.
55   *
56 < * An application can increase the capacity of an <tt>ArrayList</tt> instance
57 < * before adding a large number of elements using the <tt>ensureCapacity</tt>
56 > * <p>An application can increase the capacity of an {@code ArrayList} instance
57 > * before adding a large number of elements using the {@code ensureCapacity}
58   * operation.  This may reduce the amount of incremental reallocation.
59   *
60   * <p><strong>Note that this implementation is not synchronized.</strong>
61 < * If multiple threads access an <tt>ArrayList</tt> instance concurrently,
61 > * If multiple threads access an {@code ArrayList} instance concurrently,
62   * and at least one of the threads modifies the list structurally, it
63   * <i>must</i> be synchronized externally.  (A structural modification is
64   * any operation that adds or deletes one or more elements, or explicitly
# Line 49 | Line 72 | import java.util.*; // for javadoc (till
72   * unsynchronized access to the list:<pre>
73   *   List list = Collections.synchronizedList(new ArrayList(...));</pre>
74   *
75 < * <p>The iterators returned by this class's <tt>iterator</tt> and
76 < * <tt>listIterator</tt> methods are <i>fail-fast</i>: if the list is
77 < * structurally modified at any time after the iterator is created, in any way
78 < * except through the iterator's own <tt>remove</tt> or <tt>add</tt> methods,
79 < * the iterator will throw a {@link ConcurrentModificationException}.  Thus, in
80 < * the face of concurrent modification, the iterator fails quickly and cleanly,
81 < * rather than risking arbitrary, non-deterministic behavior at an undetermined
82 < * time in the future.<p>
75 > * <p id="fail-fast">
76 > * The iterators returned by this class's {@link #iterator() iterator} and
77 > * {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
78 > * if the list is structurally modified at any time after the iterator is
79 > * created, in any way except through the iterator's own
80 > * {@link ListIterator#remove() remove} or
81 > * {@link ListIterator#add(Object) add} methods, the iterator will throw a
82 > * {@link ConcurrentModificationException}.  Thus, in the face of
83 > * concurrent modification, the iterator fails quickly and cleanly, rather
84 > * than risking arbitrary, non-deterministic behavior at an undetermined
85 > * time in the future.
86   *
87 < * Note that the fail-fast behavior of an iterator cannot be guaranteed
87 > * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
88   * as it is, generally speaking, impossible to make any hard guarantees in the
89   * presence of unsynchronized concurrent modification.  Fail-fast iterators
90 < * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
90 > * throw {@code ConcurrentModificationException} on a best-effort basis.
91   * Therefore, it would be wrong to write a program that depended on this
92 < * exception for its correctness: <i>the fail-fast behavior of iterators
93 < * should be used only to detect bugs.</i><p>
92 > * exception for its correctness:  <i>the fail-fast behavior of iterators
93 > * should be used only to detect bugs.</i>
94   *
95 < * This class is a member of the
96 < * <a href="{@docRoot}/../guide/collections/index.html">
95 > * <p>This class is a member of the
96 > * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
97   * Java Collections Framework</a>.
98   *
99 + * @param <E> the type of elements in this list
100 + *
101   * @author  Josh Bloch
102   * @author  Neal Gafter
103 < * @version %I%, %G%
104 < * @see     Collection
105 < * @see     List
106 < * @see     LinkedList
79 < * @see     Vector
103 > * @see     Collection
104 > * @see     List
105 > * @see     LinkedList
106 > * @see     Vector
107   * @since   1.2
108   */
82
109   public class ArrayList<E> extends AbstractList<E>
110          implements List<E>, RandomAccess, Cloneable, java.io.Serializable
111   {
112 +    // OPENJDK @java.io.Serial
113      private static final long serialVersionUID = 8683452581122892189L;
114  
115      /**
116 +     * Default initial capacity.
117 +     */
118 +    private static final int DEFAULT_CAPACITY = 10;
119 +
120 +    /**
121 +     * Shared empty array instance used for empty instances.
122 +     */
123 +    private static final Object[] EMPTY_ELEMENTDATA = {};
124 +
125 +    /**
126 +     * Shared empty array instance used for default sized empty instances. We
127 +     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
128 +     * first element is added.
129 +     */
130 +    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
131 +
132 +    /**
133       * The array buffer into which the elements of the ArrayList are stored.
134 <     * The capacity of the ArrayList is the length of this array buffer.
134 >     * The capacity of the ArrayList is the length of this array buffer. Any
135 >     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
136 >     * will be expanded to DEFAULT_CAPACITY when the first element is added.
137       */
138 <    private transient Object[] elementData;
138 >    transient Object[] elementData; // non-private to simplify nested class access
139  
140      /**
141       * The size of the ArrayList (the number of elements it contains).
# Line 101 | Line 147 | public class ArrayList<E> extends Abstra
147      /**
148       * Constructs an empty list with the specified initial capacity.
149       *
150 <     * @param initialCapacity the initial capacity of the list
150 >     * @param  initialCapacity  the initial capacity of the list
151       * @throws IllegalArgumentException if the specified initial capacity
152       *         is negative
153       */
154      public ArrayList(int initialCapacity) {
155 <        super();
156 <        if (initialCapacity < 0)
155 >        if (initialCapacity > 0) {
156 >            this.elementData = new Object[initialCapacity];
157 >        } else if (initialCapacity == 0) {
158 >            this.elementData = EMPTY_ELEMENTDATA;
159 >        } else {
160              throw new IllegalArgumentException("Illegal Capacity: "+
161                                                 initialCapacity);
162 <        this.elementData = new Object[initialCapacity];
162 >        }
163      }
164  
165      /**
166       * Constructs an empty list with an initial capacity of ten.
167       */
168      public ArrayList() {
169 <        this(10);
169 >        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
170      }
171  
172      /**
173       * Constructs a list containing the elements of the specified
174       * collection, in the order they are returned by the collection's
175 <     * iterator.  The <tt>ArrayList</tt> instance has an initial capacity of
127 <     * 110% the size of the specified collection.
175 >     * iterator.
176       *
177       * @param c the collection whose elements are to be placed into this list
178       * @throws NullPointerException if the specified collection is null
179       */
180      public ArrayList(Collection<? extends E> c) {
181 <        int size = c.size();
182 <        // 10% for growth
183 <        int cap = ((size/10)+1)*11;
184 <        if (cap > 0) {
185 <            Object[] a = new Object[cap];
186 <            a[size] = a[size+1] = UNALLOCATED;
187 <            Object[] b = c.toArray(a);
188 <            if (b[size] == null && b[size+1] == UNALLOCATED) {
189 <                b[size+1] = null;
190 <                elementData = b;
143 <                this.size = size;
144 <                return;
145 <            }
146 <        }
147 <        initFromConcurrentlyMutating(c);
148 <    }
149 <
150 <    private void initFromConcurrentlyMutating(Collection<? extends E> c) {
151 <        elementData = c.toArray();
152 <        size = elementData.length;
153 <        // c.toArray might (incorrectly) not return Object[] (see 6260652)
154 <        if (elementData.getClass() != Object[].class)
155 <            elementData = Arrays.copyOf(elementData, size, Object[].class);
181 >        elementData = c.toArray();
182 >        if ((size = elementData.length) != 0) {
183 >            // defend against c.toArray (incorrectly) not returning Object[]
184 >            // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
185 >            if (elementData.getClass() != Object[].class)
186 >                elementData = Arrays.copyOf(elementData, size, Object[].class);
187 >        } else {
188 >            // replace with empty array.
189 >            this.elementData = EMPTY_ELEMENTDATA;
190 >        }
191      }
192  
158    private final static Object UNALLOCATED = new Object();
159
193      /**
194 <     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
194 >     * Trims the capacity of this {@code ArrayList} instance to be the
195       * list's current size.  An application can use this operation to minimize
196 <     * the storage of an <tt>ArrayList</tt> instance.
196 >     * the storage of an {@code ArrayList} instance.
197       */
198      public void trimToSize() {
199 <        modCount++;
200 <        int oldCapacity = elementData.length;
201 <        if (size < oldCapacity) {
202 <            elementData = Arrays.copyOf(elementData, size);
203 <        }
199 >        modCount++;
200 >        if (size < elementData.length) {
201 >            elementData = (size == 0)
202 >              ? EMPTY_ELEMENTDATA
203 >              : Arrays.copyOf(elementData, size);
204 >        }
205      }
206  
207      /**
208 <     * Increases the capacity of this <tt>ArrayList</tt> instance, if
208 >     * Increases the capacity of this {@code ArrayList} instance, if
209       * necessary, to ensure that it can hold at least the number of elements
210       * specified by the minimum capacity argument.
211       *
212       * @param minCapacity the desired minimum capacity
213       */
214      public void ensureCapacity(int minCapacity) {
215 <        modCount++;
216 <        if (minCapacity > elementData.length)
217 <            growArray(minCapacity);
215 >        if (minCapacity > elementData.length
216 >            && !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
217 >                 && minCapacity <= DEFAULT_CAPACITY)) {
218 >            modCount++;
219 >            grow(minCapacity);
220 >        }
221      }
222  
223      /**
224 <     * Increases the capacity of the array.
224 >     * Increases the capacity to ensure that it can hold at least the
225 >     * number of elements specified by the minimum capacity argument.
226       *
227       * @param minCapacity the desired minimum capacity
228 +     * @throws OutOfMemoryError if minCapacity is less than zero
229       */
230 <    private void growArray(int minCapacity) {
231 <        if (minCapacity < 0) // overflow
232 <            throw new OutOfMemoryError();
233 <        int oldCapacity = elementData.length;
234 <        // Double size if small; else grow by 50%
235 <        int newCapacity = ((oldCapacity < 64)?
236 <                           ((oldCapacity + 1) * 2):
237 <                           ((oldCapacity / 2) * 3));
238 <        if (newCapacity < 0) // overflow
239 <            newCapacity = Integer.MAX_VALUE;
240 <        if (newCapacity < minCapacity)
241 <            newCapacity = minCapacity;
242 <        elementData = Arrays.copyOf(elementData, newCapacity);
230 >    private Object[] grow(int minCapacity) {
231 >        int oldCapacity = elementData.length;
232 >        if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
233 >            int newCapacity = ArraysSupport.newLength(oldCapacity,
234 >                    minCapacity - oldCapacity, /* minimum growth */
235 >                    oldCapacity >> 1           /* preferred growth */);
236 >            return elementData = Arrays.copyOf(elementData, newCapacity);
237 >        } else {
238 >            return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
239 >        }
240 >    }
241 >
242 >    private Object[] grow() {
243 >        return grow(size + 1);
244      }
245  
246      /**
# Line 209 | Line 249 | public class ArrayList<E> extends Abstra
249       * @return the number of elements in this list
250       */
251      public int size() {
252 <        return size;
252 >        return size;
253      }
254  
255      /**
256 <     * Returns <tt>true</tt> if this list contains no elements.
256 >     * Returns {@code true} if this list contains no elements.
257       *
258 <     * @return <tt>true</tt> if this list contains no elements
258 >     * @return {@code true} if this list contains no elements
259       */
260      public boolean isEmpty() {
261 <        return size == 0;
261 >        return size == 0;
262      }
263  
264      /**
265 <     * Returns <tt>true</tt> if this list contains the specified element.
266 <     * More formally, returns <tt>true</tt> if and only if this list contains
267 <     * at least one element <tt>e</tt> such that
268 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
265 >     * Returns {@code true} if this list contains the specified element.
266 >     * More formally, returns {@code true} if and only if this list contains
267 >     * at least one element {@code e} such that
268 >     * {@code Objects.equals(o, e)}.
269       *
270       * @param o element whose presence in this list is to be tested
271 <     * @return <tt>true</tt> if this list contains the specified element
271 >     * @return {@code true} if this list contains the specified element
272       */
273      public boolean contains(Object o) {
274 <        return indexOf(o) >= 0;
274 >        return indexOf(o) >= 0;
275      }
276  
277      /**
278       * Returns the index of the first occurrence of the specified element
279       * in this list, or -1 if this list does not contain the element.
280 <     * More formally, returns the lowest index <tt>i</tt> such that
281 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
280 >     * More formally, returns the lowest index {@code i} such that
281 >     * {@code Objects.equals(o, get(i))},
282       * or -1 if there is no such index.
283       */
284      public int indexOf(Object o) {
285 <        if (o == null) {
286 <            for (int i = 0; i < size; i++)
287 <                if (elementData[i]==null)
288 <                    return i;
289 <        } else {
290 <            for (int i = 0; i < size; i++)
291 <                if (o.equals(elementData[i]))
292 <                    return i;
293 <        }
294 <        return -1;
285 >        return indexOfRange(o, 0, size);
286 >    }
287 >
288 >    int indexOfRange(Object o, int start, int end) {
289 >        Object[] es = elementData;
290 >        if (o == null) {
291 >            for (int i = start; i < end; i++) {
292 >                if (es[i] == null) {
293 >                    return i;
294 >                }
295 >            }
296 >        } else {
297 >            for (int i = start; i < end; i++) {
298 >                if (o.equals(es[i])) {
299 >                    return i;
300 >                }
301 >            }
302 >        }
303 >        return -1;
304      }
305  
306      /**
307       * Returns the index of the last occurrence of the specified element
308       * in this list, or -1 if this list does not contain the element.
309 <     * More formally, returns the highest index <tt>i</tt> such that
310 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
309 >     * More formally, returns the highest index {@code i} such that
310 >     * {@code Objects.equals(o, get(i))},
311       * or -1 if there is no such index.
312       */
313      public int lastIndexOf(Object o) {
314 <        if (o == null) {
315 <            for (int i = size-1; i >= 0; i--)
316 <                if (elementData[i]==null)
317 <                    return i;
318 <        } else {
319 <            for (int i = size-1; i >= 0; i--)
320 <                if (o.equals(elementData[i]))
321 <                    return i;
322 <        }
323 <        return -1;
314 >        return lastIndexOfRange(o, 0, size);
315 >    }
316 >
317 >    int lastIndexOfRange(Object o, int start, int end) {
318 >        Object[] es = elementData;
319 >        if (o == null) {
320 >            for (int i = end - 1; i >= start; i--) {
321 >                if (es[i] == null) {
322 >                    return i;
323 >                }
324 >            }
325 >        } else {
326 >            for (int i = end - 1; i >= start; i--) {
327 >                if (o.equals(es[i])) {
328 >                    return i;
329 >                }
330 >            }
331 >        }
332 >        return -1;
333      }
334  
335      /**
336 <     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
336 >     * Returns a shallow copy of this {@code ArrayList} instance.  (The
337       * elements themselves are not copied.)
338       *
339 <     * @return a clone of this <tt>ArrayList</tt> instance
339 >     * @return a clone of this {@code ArrayList} instance
340       */
341      public Object clone() {
342 <        try {
343 <            ArrayList<E> v = (ArrayList<E>) super.clone();
344 <            v.elementData = Arrays.copyOf(elementData, size);
345 <            v.modCount = 0;
346 <            return v;
347 <        } catch (CloneNotSupportedException e) {
348 <            // this shouldn't happen, since we are Cloneable
349 <            throw new InternalError();
350 <        }
342 >        try {
343 >            ArrayList<?> v = (ArrayList<?>) super.clone();
344 >            v.elementData = Arrays.copyOf(elementData, size);
345 >            v.modCount = 0;
346 >            return v;
347 >        } catch (CloneNotSupportedException e) {
348 >            // this shouldn't happen, since we are Cloneable
349 >            throw new InternalError(e);
350 >        }
351      }
352  
353      /**
# Line 321 | Line 379 | public class ArrayList<E> extends Abstra
379       * <p>If the list fits in the specified array with room to spare
380       * (i.e., the array has more elements than the list), the element in
381       * the array immediately following the end of the collection is set to
382 <     * <tt>null</tt>.  (This is useful in determining the length of the
382 >     * {@code null}.  (This is useful in determining the length of the
383       * list <i>only</i> if the caller knows that the list does not contain
384       * any null elements.)
385       *
# Line 334 | Line 392 | public class ArrayList<E> extends Abstra
392       *         this list
393       * @throws NullPointerException if the specified array is null
394       */
395 +    @SuppressWarnings("unchecked")
396      public <T> T[] toArray(T[] a) {
397          if (a.length < size)
398              // Make a new array of a's runtime type, but my contents:
399              return (T[]) Arrays.copyOf(elementData, size, a.getClass());
400 <        System.arraycopy(elementData, 0, a, 0, size);
400 >        System.arraycopy(elementData, 0, a, 0, size);
401          if (a.length > size)
402              a[size] = null;
403          return a;
# Line 346 | Line 405 | public class ArrayList<E> extends Abstra
405  
406      // Positional Access Operations
407  
408 <    /**
409 <     * Returns error message string for IndexOutOfBoundsExceptions
410 <     */
411 <    private String ioobe(int index) {
412 <        return "Index: " + index + ", Size: " + size;
408 >    @SuppressWarnings("unchecked")
409 >    E elementData(int index) {
410 >        return (E) elementData[index];
411 >    }
412 >
413 >    @SuppressWarnings("unchecked")
414 >    static <E> E elementAt(Object[] es, int index) {
415 >        return (E) es[index];
416      }
417  
418      /**
# Line 361 | Line 423 | public class ArrayList<E> extends Abstra
423       * @throws IndexOutOfBoundsException {@inheritDoc}
424       */
425      public E get(int index) {
426 <        if (index >= size)
427 <            throw new IndexOutOfBoundsException(ioobe(index));
366 <        return (E)elementData[index];
426 >        Objects.checkIndex(index, size);
427 >        return elementData(index);
428      }
429  
430      /**
# Line 376 | Line 437 | public class ArrayList<E> extends Abstra
437       * @throws IndexOutOfBoundsException {@inheritDoc}
438       */
439      public E set(int index, E element) {
440 <        if (index >= size)
441 <            throw new IndexOutOfBoundsException(ioobe(index));
440 >        Objects.checkIndex(index, size);
441 >        E oldValue = elementData(index);
442 >        elementData[index] = element;
443 >        return oldValue;
444 >    }
445  
446 <        E oldValue = (E) elementData[index];
447 <        elementData[index] = element;
448 <        return oldValue;
446 >    /**
447 >     * This helper method split out from add(E) to keep method
448 >     * bytecode size under 35 (the -XX:MaxInlineSize default value),
449 >     * which helps when add(E) is called in a C1-compiled loop.
450 >     */
451 >    private void add(E e, Object[] elementData, int s) {
452 >        if (s == elementData.length)
453 >            elementData = grow();
454 >        elementData[s] = e;
455 >        size = s + 1;
456      }
457  
458      /**
459       * Appends the specified element to the end of this list.
460       *
461       * @param e element to be appended to this list
462 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
462 >     * @return {@code true} (as specified by {@link Collection#add})
463       */
464      public boolean add(E e) {
465          modCount++;
466 <        int s = size;
467 <        if (s >= elementData.length)
397 <            growArray(s + 1);
398 <        elementData[s] = e;
399 <        size = s + 1;
400 <        return true;
466 >        add(e, elementData, size);
467 >        return true;
468      }
469  
470      /**
# Line 410 | Line 477 | public class ArrayList<E> extends Abstra
477       * @throws IndexOutOfBoundsException {@inheritDoc}
478       */
479      public void add(int index, E element) {
480 <        int s = size;
414 <        if (index > s || index < 0)
415 <            throw new IndexOutOfBoundsException(ioobe(index));
480 >        rangeCheckForAdd(index);
481          modCount++;
482 <        if (s >= elementData.length)
483 <            growArray(s + 1);
484 <        System.arraycopy(elementData, index,
485 <                         elementData, index + 1, s - index);
486 <        elementData[index] = element;
482 >        final int s;
483 >        Object[] elementData;
484 >        if ((s = size) == (elementData = this.elementData).length)
485 >            elementData = grow();
486 >        System.arraycopy(elementData, index,
487 >                         elementData, index + 1,
488 >                         s - index);
489 >        elementData[index] = element;
490          size = s + 1;
491 +        // checkInvariants();
492      }
493  
494      /**
# Line 432 | Line 501 | public class ArrayList<E> extends Abstra
501       * @throws IndexOutOfBoundsException {@inheritDoc}
502       */
503      public E remove(int index) {
504 <        int s = size - 1;
505 <        if (index > s)
506 <            throw new IndexOutOfBoundsException(ioobe(index));
507 <        modCount++;
508 <        E oldValue = (E)elementData[index];
509 <        int numMoved = s - index;
510 <        if (numMoved > 0)
511 <            System.arraycopy(elementData, index + 1,
512 <                             elementData, index, numMoved);
513 <        elementData[s] = null;
514 <        size = s;
515 <        return oldValue;
504 >        Objects.checkIndex(index, size);
505 >        final Object[] es = elementData;
506 >
507 >        @SuppressWarnings("unchecked") E oldValue = (E) es[index];
508 >        fastRemove(es, index);
509 >
510 >        // checkInvariants();
511 >        return oldValue;
512 >    }
513 >
514 >    /**
515 >     * {@inheritDoc}
516 >     */
517 >    public boolean equals(Object o) {
518 >        if (o == this) {
519 >            return true;
520 >        }
521 >
522 >        if (!(o instanceof List)) {
523 >            return false;
524 >        }
525 >
526 >        final int expectedModCount = modCount;
527 >        // ArrayList can be subclassed and given arbitrary behavior, but we can
528 >        // still deal with the common case where o is ArrayList precisely
529 >        boolean equal = (o.getClass() == ArrayList.class)
530 >            ? equalsArrayList((ArrayList<?>) o)
531 >            : equalsRange((List<?>) o, 0, size);
532 >
533 >        checkForComodification(expectedModCount);
534 >        return equal;
535 >    }
536 >
537 >    boolean equalsRange(List<?> other, int from, int to) {
538 >        final Object[] es = elementData;
539 >        if (to > es.length) {
540 >            throw new ConcurrentModificationException();
541 >        }
542 >        var oit = other.iterator();
543 >        for (; from < to; from++) {
544 >            if (!oit.hasNext() || !Objects.equals(es[from], oit.next())) {
545 >                return false;
546 >            }
547 >        }
548 >        return !oit.hasNext();
549 >    }
550 >
551 >    private boolean equalsArrayList(ArrayList<?> other) {
552 >        final int otherModCount = other.modCount;
553 >        final int s = size;
554 >        boolean equal;
555 >        if (equal = (s == other.size)) {
556 >            final Object[] otherEs = other.elementData;
557 >            final Object[] es = elementData;
558 >            if (s > es.length || s > otherEs.length) {
559 >                throw new ConcurrentModificationException();
560 >            }
561 >            for (int i = 0; i < s; i++) {
562 >                if (!Objects.equals(es[i], otherEs[i])) {
563 >                    equal = false;
564 >                    break;
565 >                }
566 >            }
567 >        }
568 >        other.checkForComodification(otherModCount);
569 >        return equal;
570 >    }
571 >
572 >    private void checkForComodification(final int expectedModCount) {
573 >        if (modCount != expectedModCount) {
574 >            throw new ConcurrentModificationException();
575 >        }
576 >    }
577 >
578 >    /**
579 >     * {@inheritDoc}
580 >     */
581 >    public int hashCode() {
582 >        int expectedModCount = modCount;
583 >        int hash = hashCodeRange(0, size);
584 >        checkForComodification(expectedModCount);
585 >        return hash;
586 >    }
587 >
588 >    int hashCodeRange(int from, int to) {
589 >        final Object[] es = elementData;
590 >        if (to > es.length) {
591 >            throw new ConcurrentModificationException();
592 >        }
593 >        int hashCode = 1;
594 >        for (int i = from; i < to; i++) {
595 >            Object e = es[i];
596 >            hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
597 >        }
598 >        return hashCode;
599      }
600  
601      /**
602       * Removes the first occurrence of the specified element from this list,
603       * if it is present.  If the list does not contain the element, it is
604       * unchanged.  More formally, removes the element with the lowest index
605 <     * <tt>i</tt> such that
606 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
607 <     * (if such an element exists).  Returns <tt>true</tt> if this list
605 >     * {@code i} such that
606 >     * {@code Objects.equals(o, get(i))}
607 >     * (if such an element exists).  Returns {@code true} if this list
608       * contained the specified element (or equivalently, if this list
609       * changed as a result of the call).
610       *
611       * @param o element to be removed from this list, if present
612 <     * @return <tt>true</tt> if this list contained the specified element
612 >     * @return {@code true} if this list contained the specified element
613       */
614      public boolean remove(Object o) {
615 <        if (o == null) {
616 <            for (int index = 0; index < size; index++)
617 <                if (elementData[index] == null) {
618 <                    fastRemove(index);
619 <                    return true;
620 <                }
621 <        } else {
622 <            for (int index = 0; index < size; index++)
623 <                if (o.equals(elementData[index])) {
624 <                    fastRemove(index);
625 <                    return true;
626 <                }
615 >        final Object[] es = elementData;
616 >        final int size = this.size;
617 >        int i = 0;
618 >        found: {
619 >            if (o == null) {
620 >                for (; i < size; i++)
621 >                    if (es[i] == null)
622 >                        break found;
623 >            } else {
624 >                for (; i < size; i++)
625 >                    if (o.equals(es[i]))
626 >                        break found;
627 >            }
628 >            return false;
629          }
630 <        return false;
630 >        fastRemove(es, i);
631 >        return true;
632      }
633  
634 <    /*
634 >    /**
635       * Private remove method that skips bounds checking and does not
636       * return the value removed.
637       */
638 <    private void fastRemove(int index) {
638 >    private void fastRemove(Object[] es, int i) {
639          modCount++;
640 <        int numMoved = size - index - 1;
641 <        if (numMoved > 0)
642 <            System.arraycopy(elementData, index+1, elementData, index,
643 <                             numMoved);
489 <        elementData[--size] = null; // Let gc do its work
640 >        final int newSize;
641 >        if ((newSize = size - 1) > i)
642 >            System.arraycopy(es, i + 1, es, i, newSize - i);
643 >        es[size = newSize] = null;
644      }
645  
646      /**
# Line 494 | Line 648 | public class ArrayList<E> extends Abstra
648       * be empty after this call returns.
649       */
650      public void clear() {
651 <        modCount++;
652 <
653 <        // Let gc do its work
654 <        for (int i = 0; i < size; i++)
501 <            elementData[i] = null;
502 <
503 <        size = 0;
651 >        modCount++;
652 >        final Object[] es = elementData;
653 >        for (int to = size, i = size = 0; i < to; i++)
654 >            es[i] = null;
655      }
656  
657      /**
# Line 513 | Line 664 | public class ArrayList<E> extends Abstra
664       * list is nonempty.)
665       *
666       * @param c collection containing elements to be added to this list
667 <     * @return <tt>true</tt> if this list changed as a result of the call
667 >     * @return {@code true} if this list changed as a result of the call
668       * @throws NullPointerException if the specified collection is null
669       */
670      public boolean addAll(Collection<? extends E> c) {
671 <        Object[] a = c.toArray();
671 >        Object[] a = c.toArray();
672 >        modCount++;
673          int numNew = a.length;
674 <        ensureCapacity(size + numNew);  // Increments modCount
675 <        System.arraycopy(a, 0, elementData, size, numNew);
676 <        size += numNew;
677 <        return numNew != 0;
674 >        if (numNew == 0)
675 >            return false;
676 >        Object[] elementData;
677 >        final int s;
678 >        if (numNew > (elementData = this.elementData).length - (s = size))
679 >            elementData = grow(s + numNew);
680 >        System.arraycopy(a, 0, elementData, s, numNew);
681 >        size = s + numNew;
682 >        // checkInvariants();
683 >        return true;
684      }
685  
686      /**
# Line 536 | Line 694 | public class ArrayList<E> extends Abstra
694       * @param index index at which to insert the first element from the
695       *              specified collection
696       * @param c collection containing elements to be added to this list
697 <     * @return <tt>true</tt> if this list changed as a result of the call
697 >     * @return {@code true} if this list changed as a result of the call
698       * @throws IndexOutOfBoundsException {@inheritDoc}
699       * @throws NullPointerException if the specified collection is null
700       */
701      public boolean addAll(int index, Collection<? extends E> c) {
702 <        if (index > size || index < 0)
545 <            throw new IndexOutOfBoundsException(ioobe(index));
702 >        rangeCheckForAdd(index);
703  
704 <        Object[] a = c.toArray();
705 <        int numNew = a.length;
706 <        ensureCapacity(size + numNew);  // Increments modCount
707 <
708 <        int numMoved = size - index;
709 <        if (numMoved > 0)
710 <            System.arraycopy(elementData, index, elementData, index + numNew,
711 <                             numMoved);
704 >        Object[] a = c.toArray();
705 >        modCount++;
706 >        int numNew = a.length;
707 >        if (numNew == 0)
708 >            return false;
709 >        Object[] elementData;
710 >        final int s;
711 >        if (numNew > (elementData = this.elementData).length - (s = size))
712 >            elementData = grow(s + numNew);
713  
714 +        int numMoved = s - index;
715 +        if (numMoved > 0)
716 +            System.arraycopy(elementData, index,
717 +                             elementData, index + numNew,
718 +                             numMoved);
719          System.arraycopy(a, 0, elementData, index, numNew);
720 <        size += numNew;
721 <        return numNew != 0;
720 >        size = s + numNew;
721 >        // checkInvariants();
722 >        return true;
723      }
724  
725      /**
726       * Removes from this list all of the elements whose index is between
727 <     * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.
727 >     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
728       * Shifts any succeeding elements to the left (reduces their index).
729 <     * This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
730 <     * (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
729 >     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
730 >     * (If {@code toIndex==fromIndex}, this operation has no effect.)
731       *
732 <     * @param fromIndex index of first element to be removed
733 <     * @param toIndex index after last element to be removed
734 <     * @throws IndexOutOfBoundsException if fromIndex or toIndex out of
735 <     *              range (fromIndex &lt; 0 || fromIndex &gt;= size() || toIndex
736 <     *              &gt; size() || toIndex &lt; fromIndex)
732 >     * @throws IndexOutOfBoundsException if {@code fromIndex} or
733 >     *         {@code toIndex} is out of range
734 >     *         ({@code fromIndex < 0 ||
735 >     *          toIndex > size() ||
736 >     *          toIndex < fromIndex})
737       */
738      protected void removeRange(int fromIndex, int toIndex) {
739 <        modCount++;
740 <        int numMoved = size - toIndex;
741 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
742 <                         numMoved);
739 >        if (fromIndex > toIndex) {
740 >            throw new IndexOutOfBoundsException(
741 >                    outOfBoundsMsg(fromIndex, toIndex));
742 >        }
743 >        modCount++;
744 >        shiftTailOverGap(elementData, fromIndex, toIndex);
745 >        // checkInvariants();
746 >    }
747  
748 <        // Let gc do its work
749 <        int newSize = size - (toIndex-fromIndex);
750 <        while (size != newSize)
751 <            elementData[--size] = null;
748 >    /** Erases the gap from lo to hi, by sliding down following elements. */
749 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
750 >        System.arraycopy(es, hi, es, lo, size - hi);
751 >        for (int to = size, i = (size -= hi - lo); i < to; i++)
752 >            es[i] = null;
753      }
754  
755      /**
756 <     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
757 <     * is, serialize it).
756 >     * A version of rangeCheck used by add and addAll.
757 >     */
758 >    private void rangeCheckForAdd(int index) {
759 >        if (index > size || index < 0)
760 >            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
761 >    }
762 >
763 >    /**
764 >     * Constructs an IndexOutOfBoundsException detail message.
765 >     * Of the many possible refactorings of the error handling code,
766 >     * this "outlining" performs best with both server and client VMs.
767 >     */
768 >    private String outOfBoundsMsg(int index) {
769 >        return "Index: "+index+", Size: "+size;
770 >    }
771 >
772 >    /**
773 >     * A version used in checking (fromIndex > toIndex) condition
774 >     */
775 >    private static String outOfBoundsMsg(int fromIndex, int toIndex) {
776 >        return "From Index: " + fromIndex + " > To Index: " + toIndex;
777 >    }
778 >
779 >    /**
780 >     * Removes from this list all of its elements that are contained in the
781 >     * specified collection.
782       *
783 <     * @serialData The length of the array backing the <tt>ArrayList</tt>
783 >     * @param c collection containing elements to be removed from this list
784 >     * @return {@code true} if this list changed as a result of the call
785 >     * @throws ClassCastException if the class of an element of this list
786 >     *         is incompatible with the specified collection
787 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
788 >     * @throws NullPointerException if this list contains a null element and the
789 >     *         specified collection does not permit null elements
790 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
791 >     *         or if the specified collection is null
792 >     * @see Collection#contains(Object)
793 >     */
794 >    public boolean removeAll(Collection<?> c) {
795 >        return batchRemove(c, false, 0, size);
796 >    }
797 >
798 >    /**
799 >     * Retains only the elements in this list that are contained in the
800 >     * specified collection.  In other words, removes from this list all
801 >     * of its elements that are not contained in the specified collection.
802 >     *
803 >     * @param c collection containing elements to be retained in this list
804 >     * @return {@code true} if this list changed as a result of the call
805 >     * @throws ClassCastException if the class of an element of this list
806 >     *         is incompatible with the specified collection
807 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
808 >     * @throws NullPointerException if this list contains a null element and the
809 >     *         specified collection does not permit null elements
810 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
811 >     *         or if the specified collection is null
812 >     * @see Collection#contains(Object)
813 >     */
814 >    public boolean retainAll(Collection<?> c) {
815 >        return batchRemove(c, true, 0, size);
816 >    }
817 >
818 >    boolean batchRemove(Collection<?> c, boolean complement,
819 >                        final int from, final int end) {
820 >        Objects.requireNonNull(c);
821 >        final Object[] es = elementData;
822 >        int r;
823 >        // Optimize for initial run of survivors
824 >        for (r = from;; r++) {
825 >            if (r == end)
826 >                return false;
827 >            if (c.contains(es[r]) != complement)
828 >                break;
829 >        }
830 >        int w = r++;
831 >        try {
832 >            for (Object e; r < end; r++)
833 >                if (c.contains(e = es[r]) == complement)
834 >                    es[w++] = e;
835 >        } catch (Throwable ex) {
836 >            // Preserve behavioral compatibility with AbstractCollection,
837 >            // even if c.contains() throws.
838 >            System.arraycopy(es, r, es, w, end - r);
839 >            w += end - r;
840 >            throw ex;
841 >        } finally {
842 >            modCount += end - w;
843 >            shiftTailOverGap(es, w, end);
844 >        }
845 >        // checkInvariants();
846 >        return true;
847 >    }
848 >
849 >    /**
850 >     * Saves the state of the {@code ArrayList} instance to a stream
851 >     * (that is, serializes it).
852 >     *
853 >     * @param s the stream
854 >     * @throws java.io.IOException if an I/O error occurs
855 >     * @serialData The length of the array backing the {@code ArrayList}
856       *             instance is emitted (int), followed by all of its elements
857 <     *             (each an <tt>Object</tt>) in the proper order.
857 >     *             (each an {@code Object}) in the proper order.
858       */
859 +    // OPENJDK @java.io.Serial
860      private void writeObject(java.io.ObjectOutputStream s)
861 <        throws java.io.IOException{
862 <        // Write out element count, and any hidden stuff
863 <        int expectedModCount = modCount;
864 <        s.defaultWriteObject();
861 >        throws java.io.IOException {
862 >        // Write out element count, and any hidden stuff
863 >        int expectedModCount = modCount;
864 >        s.defaultWriteObject();
865  
866 <        // Write out array length
867 <        s.writeInt(elementData.length);
866 >        // Write out size as capacity for behavioral compatibility with clone()
867 >        s.writeInt(size);
868  
869 <        // Write out all elements in the proper order.
870 <        for (int i=0; i<size; i++)
869 >        // Write out all elements in the proper order.
870 >        for (int i=0; i<size; i++) {
871              s.writeObject(elementData[i]);
872 +        }
873  
874 <        if (expectedModCount != modCount) {
874 >        if (modCount != expectedModCount) {
875              throw new ConcurrentModificationException();
876          }
610
877      }
878  
879      /**
880 <     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
881 <     * deserialize it).
880 >     * Reconstitutes the {@code ArrayList} instance from a stream (that is,
881 >     * deserializes it).
882 >     * @param s the stream
883 >     * @throws ClassNotFoundException if the class of a serialized object
884 >     *         could not be found
885 >     * @throws java.io.IOException if an I/O error occurs
886       */
887 +    // OPENJDK @java.io.Serial
888      private void readObject(java.io.ObjectInputStream s)
889          throws java.io.IOException, ClassNotFoundException {
619        // Read in size, and any hidden stuff
620        s.defaultReadObject();
890  
891 <        // Read in array length and allocate array
892 <        int arrayLength = s.readInt();
624 <        Object[] a = elementData = new Object[arrayLength];
891 >        // Read in size, and any hidden stuff
892 >        s.defaultReadObject();
893  
894 <        // Read in all elements in the proper order.
895 <        for (int i=0; i<size; i++)
628 <            a[i] = s.readObject();
629 <    }
894 >        // Read in capacity
895 >        s.readInt(); // ignored
896  
897 +        if (size > 0) {
898 +            // like clone(), allocate array based upon size not capacity
899 +            jsr166.Platform.checkArray(s, Object[].class, size);
900 +            Object[] elements = new Object[size];
901 +
902 +            // Read in all elements in the proper order.
903 +            for (int i = 0; i < size; i++) {
904 +                elements[i] = s.readObject();
905 +            }
906 +
907 +            elementData = elements;
908 +        } else if (size == 0) {
909 +            elementData = EMPTY_ELEMENTDATA;
910 +        } else {
911 +            throw new java.io.InvalidObjectException("Invalid size: " + size);
912 +        }
913 +    }
914  
915      /**
916 <     * Returns a list-iterator of the elements in this list (in proper
916 >     * Returns a list iterator over the elements in this list (in proper
917       * sequence), starting at the specified position in the list.
918 <     * Obeys the general contract of <tt>List.listIterator(int)</tt>.<p>
918 >     * The specified index indicates the first element that would be
919 >     * returned by an initial call to {@link ListIterator#next next}.
920 >     * An initial call to {@link ListIterator#previous previous} would
921 >     * return the element with the specified index minus one.
922 >     *
923 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
924       *
637     * The list-iterator is <i>fail-fast</i>: if the list is structurally
638     * modified at any time after the Iterator is created, in any way except
639     * through the list-iterator's own <tt>remove</tt> or <tt>add</tt>
640     * methods, the list-iterator will throw a
641     * <tt>ConcurrentModificationException</tt>.  Thus, in the face of
642     * concurrent modification, the iterator fails quickly and cleanly, rather
643     * than risking arbitrary, non-deterministic behavior at an undetermined
644     * time in the future.
645     *
646     * @param index index of the first element to be returned from the
647     *              list-iterator (by a call to <tt>next</tt>)
648     * @return a ListIterator of the elements in this list (in proper
649     *         sequence), starting at the specified position in the list
925       * @throws IndexOutOfBoundsException {@inheritDoc}
651     * @see List#listIterator(int)
926       */
927      public ListIterator<E> listIterator(int index) {
928 <        if (index < 0 || index > size)
929 <            throw new IndexOutOfBoundsException(ioobe(index));
656 <        return new ArrayListIterator(index);
928 >        rangeCheckForAdd(index);
929 >        return new ListItr(index);
930      }
931  
932      /**
933 <     * {@inheritDoc}
933 >     * Returns a list iterator over the elements in this list (in proper
934 >     * sequence).
935 >     *
936 >     * <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
937 >     *
938 >     * @see #listIterator(int)
939       */
940      public ListIterator<E> listIterator() {
941 <        return new ArrayListIterator(0);
941 >        return new ListItr(0);
942      }
943  
944      /**
945       * Returns an iterator over the elements in this list in proper sequence.
946       *
947 +     * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
948 +     *
949       * @return an iterator over the elements in this list in proper sequence
950       */
951      public Iterator<E> iterator() {
952 <        return new ArrayListIterator(0);
952 >        return new Itr();
953      }
954  
955      /**
956 <     * A streamlined version of AbstractList.ListItr
956 >     * An optimized version of AbstractList.Itr
957       */
958 <    final class ArrayListIterator implements ListIterator<E> {
959 <        int cursor;           // index of next element to return;
960 <        int lastRet;          // index of last element, or -1 if no such
961 <        int expectedModCount; // to check for CME
958 >    private class Itr implements Iterator<E> {
959 >        int cursor;       // index of next element to return
960 >        int lastRet = -1; // index of last element returned; -1 if no such
961 >        int expectedModCount = modCount;
962  
963 <        ArrayListIterator(int index) {
964 <            cursor = index;
685 <            lastRet = -1;
686 <            expectedModCount = modCount;
687 <        }
963 >        // prevent creating a synthetic constructor
964 >        Itr() {}
965  
966 <        public boolean hasNext() {
966 >        public boolean hasNext() {
967              return cursor != size;
968 <        }
692 <
693 <        public boolean hasPrevious() {
694 <            return cursor != 0;
695 <        }
968 >        }
969  
970 <        public int nextIndex() {
971 <            return cursor;
972 <        }
970 >        @SuppressWarnings("unchecked")
971 >        public E next() {
972 >            checkForComodification();
973 >            int i = cursor;
974 >            if (i >= size)
975 >                throw new NoSuchElementException();
976 >            Object[] elementData = ArrayList.this.elementData;
977 >            if (i >= elementData.length)
978 >                throw new ConcurrentModificationException();
979 >            cursor = i + 1;
980 >            return (E) elementData[lastRet = i];
981 >        }
982  
983 <        public int previousIndex() {
984 <            return cursor - 1;
985 <        }
983 >        public void remove() {
984 >            if (lastRet < 0)
985 >                throw new IllegalStateException();
986 >            checkForComodification();
987  
705        public E next() {
988              try {
989 <                int i = cursor;
990 <                E next = get(i);
991 <                lastRet = i;
992 <                cursor = i + 1;
711 <                return next;
989 >                ArrayList.this.remove(lastRet);
990 >                cursor = lastRet;
991 >                lastRet = -1;
992 >                expectedModCount = modCount;
993              } catch (IndexOutOfBoundsException ex) {
994 <                throw new NoSuchElementException();
995 <            } finally {
996 <                if (expectedModCount != modCount)
994 >                throw new ConcurrentModificationException();
995 >            }
996 >        }
997 >
998 >        @Override
999 >        public void forEachRemaining(Consumer<? super E> action) {
1000 >            Objects.requireNonNull(action);
1001 >            final int size = ArrayList.this.size;
1002 >            int i = cursor;
1003 >            if (i < size) {
1004 >                final Object[] es = elementData;
1005 >                if (i >= es.length)
1006                      throw new ConcurrentModificationException();
1007 +                for (; i < size && modCount == expectedModCount; i++)
1008 +                    action.accept(elementAt(es, i));
1009 +                // update once at end to reduce heap write traffic
1010 +                cursor = i;
1011 +                lastRet = i - 1;
1012 +                checkForComodification();
1013              }
1014 <        }
1014 >        }
1015  
1016 +        final void checkForComodification() {
1017 +            if (modCount != expectedModCount)
1018 +                throw new ConcurrentModificationException();
1019 +        }
1020 +    }
1021 +
1022 +    /**
1023 +     * An optimized version of AbstractList.ListItr
1024 +     */
1025 +    private class ListItr extends Itr implements ListIterator<E> {
1026 +        ListItr(int index) {
1027 +            super();
1028 +            cursor = index;
1029 +        }
1030 +
1031 +        public boolean hasPrevious() {
1032 +            return cursor != 0;
1033 +        }
1034 +
1035 +        public int nextIndex() {
1036 +            return cursor;
1037 +        }
1038 +
1039 +        public int previousIndex() {
1040 +            return cursor - 1;
1041 +        }
1042 +
1043 +        @SuppressWarnings("unchecked")
1044          public E previous() {
1045 +            checkForComodification();
1046 +            int i = cursor - 1;
1047 +            if (i < 0)
1048 +                throw new NoSuchElementException();
1049 +            Object[] elementData = ArrayList.this.elementData;
1050 +            if (i >= elementData.length)
1051 +                throw new ConcurrentModificationException();
1052 +            cursor = i;
1053 +            return (E) elementData[lastRet = i];
1054 +        }
1055 +
1056 +        public void set(E e) {
1057 +            if (lastRet < 0)
1058 +                throw new IllegalStateException();
1059 +            checkForComodification();
1060 +
1061              try {
1062 <                int i = cursor - 1;
723 <                E prev = get(i);
724 <                lastRet = i;
725 <                cursor = i;
726 <                return prev;
1062 >                ArrayList.this.set(lastRet, e);
1063              } catch (IndexOutOfBoundsException ex) {
1064 <                throw new NoSuchElementException();
729 <            } finally {
730 <                if (expectedModCount != modCount)
731 <                    throw new ConcurrentModificationException();
1064 >                throw new ConcurrentModificationException();
1065              }
1066          }
1067  
1068 <        public void remove() {
1069 <            if (lastRet < 0)
1070 <                throw new IllegalStateException();
1071 <            if (expectedModCount != modCount)
1072 <                throw new ConcurrentModificationException();
1073 <            ArrayList.this.remove(lastRet);
1074 <            if (lastRet < cursor)
1075 <                cursor--;
1076 <            lastRet = -1;
1077 <            expectedModCount = modCount;
745 <        }
746 <
747 <        public void set(E e) {
748 <            if (lastRet < 0)
749 <                throw new IllegalStateException();
750 <            if (expectedModCount != modCount)
1068 >        public void add(E e) {
1069 >            checkForComodification();
1070 >
1071 >            try {
1072 >                int i = cursor;
1073 >                ArrayList.this.add(i, e);
1074 >                cursor = i + 1;
1075 >                lastRet = -1;
1076 >                expectedModCount = modCount;
1077 >            } catch (IndexOutOfBoundsException ex) {
1078                  throw new ConcurrentModificationException();
1079 <            ArrayList.this.set(lastRet, e);
1080 <            expectedModCount = modCount;
1081 <        }
1079 >            }
1080 >        }
1081 >    }
1082 >
1083 >    /**
1084 >     * Returns a view of the portion of this list between the specified
1085 >     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.  (If
1086 >     * {@code fromIndex} and {@code toIndex} are equal, the returned list is
1087 >     * empty.)  The returned list is backed by this list, so non-structural
1088 >     * changes in the returned list are reflected in this list, and vice-versa.
1089 >     * The returned list supports all of the optional list operations.
1090 >     *
1091 >     * <p>This method eliminates the need for explicit range operations (of
1092 >     * the sort that commonly exist for arrays).  Any operation that expects
1093 >     * a list can be used as a range operation by passing a subList view
1094 >     * instead of a whole list.  For example, the following idiom
1095 >     * removes a range of elements from a list:
1096 >     * <pre>
1097 >     *      list.subList(from, to).clear();
1098 >     * </pre>
1099 >     * Similar idioms may be constructed for {@link #indexOf(Object)} and
1100 >     * {@link #lastIndexOf(Object)}, and all of the algorithms in the
1101 >     * {@link Collections} class can be applied to a subList.
1102 >     *
1103 >     * <p>The semantics of the list returned by this method become undefined if
1104 >     * the backing list (i.e., this list) is <i>structurally modified</i> in
1105 >     * any way other than via the returned list.  (Structural modifications are
1106 >     * those that change the size of this list, or otherwise perturb it in such
1107 >     * a fashion that iterations in progress may yield incorrect results.)
1108 >     *
1109 >     * @throws IndexOutOfBoundsException {@inheritDoc}
1110 >     * @throws IllegalArgumentException {@inheritDoc}
1111 >     */
1112 >    public List<E> subList(int fromIndex, int toIndex) {
1113 >        subListRangeCheck(fromIndex, toIndex, size);
1114 >        return new SubList<>(this, fromIndex, toIndex);
1115 >    }
1116 >
1117 >    private static class SubList<E> extends AbstractList<E> implements RandomAccess {
1118 >        private final ArrayList<E> root;
1119 >        private final SubList<E> parent;
1120 >        private final int offset;
1121 >        private int size;
1122 >
1123 >        /**
1124 >         * Constructs a sublist of an arbitrary ArrayList.
1125 >         */
1126 >        public SubList(ArrayList<E> root, int fromIndex, int toIndex) {
1127 >            this.root = root;
1128 >            this.parent = null;
1129 >            this.offset = fromIndex;
1130 >            this.size = toIndex - fromIndex;
1131 >            this.modCount = root.modCount;
1132 >        }
1133 >
1134 >        /**
1135 >         * Constructs a sublist of another SubList.
1136 >         */
1137 >        private SubList(SubList<E> parent, int fromIndex, int toIndex) {
1138 >            this.root = parent.root;
1139 >            this.parent = parent;
1140 >            this.offset = parent.offset + fromIndex;
1141 >            this.size = toIndex - fromIndex;
1142 >            this.modCount = parent.modCount;
1143 >        }
1144 >
1145 >        public E set(int index, E element) {
1146 >            Objects.checkIndex(index, size);
1147 >            checkForComodification();
1148 >            E oldValue = root.elementData(offset + index);
1149 >            root.elementData[offset + index] = element;
1150 >            return oldValue;
1151 >        }
1152 >
1153 >        public E get(int index) {
1154 >            Objects.checkIndex(index, size);
1155 >            checkForComodification();
1156 >            return root.elementData(offset + index);
1157 >        }
1158 >
1159 >        public int size() {
1160 >            checkForComodification();
1161 >            return size;
1162 >        }
1163 >
1164 >        public void add(int index, E element) {
1165 >            rangeCheckForAdd(index);
1166 >            checkForComodification();
1167 >            root.add(offset + index, element);
1168 >            updateSizeAndModCount(1);
1169 >        }
1170 >
1171 >        public E remove(int index) {
1172 >            Objects.checkIndex(index, size);
1173 >            checkForComodification();
1174 >            E result = root.remove(offset + index);
1175 >            updateSizeAndModCount(-1);
1176 >            return result;
1177 >        }
1178 >
1179 >        protected void removeRange(int fromIndex, int toIndex) {
1180 >            checkForComodification();
1181 >            root.removeRange(offset + fromIndex, offset + toIndex);
1182 >            updateSizeAndModCount(fromIndex - toIndex);
1183 >        }
1184 >
1185 >        public boolean addAll(Collection<? extends E> c) {
1186 >            return addAll(this.size, c);
1187 >        }
1188 >
1189 >        public boolean addAll(int index, Collection<? extends E> c) {
1190 >            rangeCheckForAdd(index);
1191 >            int cSize = c.size();
1192 >            if (cSize==0)
1193 >                return false;
1194 >            checkForComodification();
1195 >            root.addAll(offset + index, c);
1196 >            updateSizeAndModCount(cSize);
1197 >            return true;
1198 >        }
1199 >
1200 >        public void replaceAll(UnaryOperator<E> operator) {
1201 >            root.replaceAllRange(operator, offset, offset + size);
1202 >        }
1203 >
1204 >        public boolean removeAll(Collection<?> c) {
1205 >            return batchRemove(c, false);
1206 >        }
1207 >
1208 >        public boolean retainAll(Collection<?> c) {
1209 >            return batchRemove(c, true);
1210 >        }
1211 >
1212 >        private boolean batchRemove(Collection<?> c, boolean complement) {
1213 >            checkForComodification();
1214 >            int oldSize = root.size;
1215 >            boolean modified =
1216 >                root.batchRemove(c, complement, offset, offset + size);
1217 >            if (modified)
1218 >                updateSizeAndModCount(root.size - oldSize);
1219 >            return modified;
1220 >        }
1221 >
1222 >        public boolean removeIf(Predicate<? super E> filter) {
1223 >            checkForComodification();
1224 >            int oldSize = root.size;
1225 >            boolean modified = root.removeIf(filter, offset, offset + size);
1226 >            if (modified)
1227 >                updateSizeAndModCount(root.size - oldSize);
1228 >            return modified;
1229 >        }
1230 >
1231 >        public Object[] toArray() {
1232 >            checkForComodification();
1233 >            return Arrays.copyOfRange(root.elementData, offset, offset + size);
1234 >        }
1235 >
1236 >        @SuppressWarnings("unchecked")
1237 >        public <T> T[] toArray(T[] a) {
1238 >            checkForComodification();
1239 >            if (a.length < size)
1240 >                return (T[]) Arrays.copyOfRange(
1241 >                        root.elementData, offset, offset + size, a.getClass());
1242 >            System.arraycopy(root.elementData, offset, a, 0, size);
1243 >            if (a.length > size)
1244 >                a[size] = null;
1245 >            return a;
1246 >        }
1247 >
1248 >        public boolean equals(Object o) {
1249 >            if (o == this) {
1250 >                return true;
1251 >            }
1252 >
1253 >            if (!(o instanceof List)) {
1254 >                return false;
1255 >            }
1256 >
1257 >            boolean equal = root.equalsRange((List<?>)o, offset, offset + size);
1258 >            checkForComodification();
1259 >            return equal;
1260 >        }
1261 >
1262 >        public int hashCode() {
1263 >            int hash = root.hashCodeRange(offset, offset + size);
1264 >            checkForComodification();
1265 >            return hash;
1266 >        }
1267 >
1268 >        public int indexOf(Object o) {
1269 >            int index = root.indexOfRange(o, offset, offset + size);
1270 >            checkForComodification();
1271 >            return index >= 0 ? index - offset : -1;
1272 >        }
1273  
1274 <        public void add(E e) {
1275 <            if (expectedModCount != modCount)
1274 >        public int lastIndexOf(Object o) {
1275 >            int index = root.lastIndexOfRange(o, offset, offset + size);
1276 >            checkForComodification();
1277 >            return index >= 0 ? index - offset : -1;
1278 >        }
1279 >
1280 >        public boolean contains(Object o) {
1281 >            return indexOf(o) >= 0;
1282 >        }
1283 >
1284 >        public Iterator<E> iterator() {
1285 >            return listIterator();
1286 >        }
1287 >
1288 >        public ListIterator<E> listIterator(int index) {
1289 >            checkForComodification();
1290 >            rangeCheckForAdd(index);
1291 >
1292 >            return new ListIterator<E>() {
1293 >                int cursor = index;
1294 >                int lastRet = -1;
1295 >                int expectedModCount = SubList.this.modCount;
1296 >
1297 >                public boolean hasNext() {
1298 >                    return cursor != SubList.this.size;
1299 >                }
1300 >
1301 >                @SuppressWarnings("unchecked")
1302 >                public E next() {
1303 >                    checkForComodification();
1304 >                    int i = cursor;
1305 >                    if (i >= SubList.this.size)
1306 >                        throw new NoSuchElementException();
1307 >                    Object[] elementData = root.elementData;
1308 >                    if (offset + i >= elementData.length)
1309 >                        throw new ConcurrentModificationException();
1310 >                    cursor = i + 1;
1311 >                    return (E) elementData[offset + (lastRet = i)];
1312 >                }
1313 >
1314 >                public boolean hasPrevious() {
1315 >                    return cursor != 0;
1316 >                }
1317 >
1318 >                @SuppressWarnings("unchecked")
1319 >                public E previous() {
1320 >                    checkForComodification();
1321 >                    int i = cursor - 1;
1322 >                    if (i < 0)
1323 >                        throw new NoSuchElementException();
1324 >                    Object[] elementData = root.elementData;
1325 >                    if (offset + i >= elementData.length)
1326 >                        throw new ConcurrentModificationException();
1327 >                    cursor = i;
1328 >                    return (E) elementData[offset + (lastRet = i)];
1329 >                }
1330 >
1331 >                public void forEachRemaining(Consumer<? super E> action) {
1332 >                    Objects.requireNonNull(action);
1333 >                    final int size = SubList.this.size;
1334 >                    int i = cursor;
1335 >                    if (i < size) {
1336 >                        final Object[] es = root.elementData;
1337 >                        if (offset + i >= es.length)
1338 >                            throw new ConcurrentModificationException();
1339 >                        for (; i < size && root.modCount == expectedModCount; i++)
1340 >                            action.accept(elementAt(es, offset + i));
1341 >                        // update once at end to reduce heap write traffic
1342 >                        cursor = i;
1343 >                        lastRet = i - 1;
1344 >                        checkForComodification();
1345 >                    }
1346 >                }
1347 >
1348 >                public int nextIndex() {
1349 >                    return cursor;
1350 >                }
1351 >
1352 >                public int previousIndex() {
1353 >                    return cursor - 1;
1354 >                }
1355 >
1356 >                public void remove() {
1357 >                    if (lastRet < 0)
1358 >                        throw new IllegalStateException();
1359 >                    checkForComodification();
1360 >
1361 >                    try {
1362 >                        SubList.this.remove(lastRet);
1363 >                        cursor = lastRet;
1364 >                        lastRet = -1;
1365 >                        expectedModCount = SubList.this.modCount;
1366 >                    } catch (IndexOutOfBoundsException ex) {
1367 >                        throw new ConcurrentModificationException();
1368 >                    }
1369 >                }
1370 >
1371 >                public void set(E e) {
1372 >                    if (lastRet < 0)
1373 >                        throw new IllegalStateException();
1374 >                    checkForComodification();
1375 >
1376 >                    try {
1377 >                        root.set(offset + lastRet, e);
1378 >                    } catch (IndexOutOfBoundsException ex) {
1379 >                        throw new ConcurrentModificationException();
1380 >                    }
1381 >                }
1382 >
1383 >                public void add(E e) {
1384 >                    checkForComodification();
1385 >
1386 >                    try {
1387 >                        int i = cursor;
1388 >                        SubList.this.add(i, e);
1389 >                        cursor = i + 1;
1390 >                        lastRet = -1;
1391 >                        expectedModCount = SubList.this.modCount;
1392 >                    } catch (IndexOutOfBoundsException ex) {
1393 >                        throw new ConcurrentModificationException();
1394 >                    }
1395 >                }
1396 >
1397 >                final void checkForComodification() {
1398 >                    if (root.modCount != expectedModCount)
1399 >                        throw new ConcurrentModificationException();
1400 >                }
1401 >            };
1402 >        }
1403 >
1404 >        public List<E> subList(int fromIndex, int toIndex) {
1405 >            subListRangeCheck(fromIndex, toIndex, size);
1406 >            return new SubList<>(this, fromIndex, toIndex);
1407 >        }
1408 >
1409 >        private void rangeCheckForAdd(int index) {
1410 >            if (index < 0 || index > this.size)
1411 >                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1412 >        }
1413 >
1414 >        private String outOfBoundsMsg(int index) {
1415 >            return "Index: "+index+", Size: "+this.size;
1416 >        }
1417 >
1418 >        private void checkForComodification() {
1419 >            if (root.modCount != modCount)
1420                  throw new ConcurrentModificationException();
1421 <            try {
1422 <                ArrayList.this.add(cursor++, e);
1423 <                lastRet = -1;
1421 >        }
1422 >
1423 >        private void updateSizeAndModCount(int sizeChange) {
1424 >            SubList<E> slist = this;
1425 >            do {
1426 >                slist.size += sizeChange;
1427 >                slist.modCount = root.modCount;
1428 >                slist = slist.parent;
1429 >            } while (slist != null);
1430 >        }
1431 >
1432 >        public Spliterator<E> spliterator() {
1433 >            checkForComodification();
1434 >
1435 >            // ArrayListSpliterator not used here due to late-binding
1436 >            return new Spliterator<E>() {
1437 >                private int index = offset; // current index, modified on advance/split
1438 >                private int fence = -1; // -1 until used; then one past last index
1439 >                private int expectedModCount; // initialized when fence set
1440 >
1441 >                private int getFence() { // initialize fence to size on first use
1442 >                    int hi; // (a specialized variant appears in method forEach)
1443 >                    if ((hi = fence) < 0) {
1444 >                        expectedModCount = modCount;
1445 >                        hi = fence = offset + size;
1446 >                    }
1447 >                    return hi;
1448 >                }
1449 >
1450 >                public ArrayList<E>.ArrayListSpliterator trySplit() {
1451 >                    int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1452 >                    // ArrayListSpliterator can be used here as the source is already bound
1453 >                    return (lo >= mid) ? null : // divide range in half unless too small
1454 >                        root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
1455 >                }
1456 >
1457 >                public boolean tryAdvance(Consumer<? super E> action) {
1458 >                    Objects.requireNonNull(action);
1459 >                    int hi = getFence(), i = index;
1460 >                    if (i < hi) {
1461 >                        index = i + 1;
1462 >                        @SuppressWarnings("unchecked") E e = (E)root.elementData[i];
1463 >                        action.accept(e);
1464 >                        if (root.modCount != expectedModCount)
1465 >                            throw new ConcurrentModificationException();
1466 >                        return true;
1467 >                    }
1468 >                    return false;
1469 >                }
1470 >
1471 >                public void forEachRemaining(Consumer<? super E> action) {
1472 >                    Objects.requireNonNull(action);
1473 >                    int i, hi, mc; // hoist accesses and checks from loop
1474 >                    ArrayList<E> lst = root;
1475 >                    Object[] a;
1476 >                    if ((a = lst.elementData) != null) {
1477 >                        if ((hi = fence) < 0) {
1478 >                            mc = modCount;
1479 >                            hi = offset + size;
1480 >                        }
1481 >                        else
1482 >                            mc = expectedModCount;
1483 >                        if ((i = index) >= 0 && (index = hi) <= a.length) {
1484 >                            for (; i < hi; ++i) {
1485 >                                @SuppressWarnings("unchecked") E e = (E) a[i];
1486 >                                action.accept(e);
1487 >                            }
1488 >                            if (lst.modCount == mc)
1489 >                                return;
1490 >                        }
1491 >                    }
1492 >                    throw new ConcurrentModificationException();
1493 >                }
1494 >
1495 >                public long estimateSize() {
1496 >                    return getFence() - index;
1497 >                }
1498 >
1499 >                public int characteristics() {
1500 >                    return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1501 >                }
1502 >            };
1503 >        }
1504 >    }
1505 >
1506 >    /**
1507 >     * @throws NullPointerException {@inheritDoc}
1508 >     */
1509 >    @Override
1510 >    public void forEach(Consumer<? super E> action) {
1511 >        Objects.requireNonNull(action);
1512 >        final int expectedModCount = modCount;
1513 >        final Object[] es = elementData;
1514 >        final int size = this.size;
1515 >        for (int i = 0; modCount == expectedModCount && i < size; i++)
1516 >            action.accept(elementAt(es, i));
1517 >        if (modCount != expectedModCount)
1518 >            throw new ConcurrentModificationException();
1519 >    }
1520 >
1521 >    /**
1522 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1523 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1524 >     * list.
1525 >     *
1526 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1527 >     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1528 >     * Overriding implementations should document the reporting of additional
1529 >     * characteristic values.
1530 >     *
1531 >     * @return a {@code Spliterator} over the elements in this list
1532 >     * @since 1.8
1533 >     */
1534 >    @Override
1535 >    public Spliterator<E> spliterator() {
1536 >        return new ArrayListSpliterator(0, -1, 0);
1537 >    }
1538 >
1539 >    /** Index-based split-by-two, lazily initialized Spliterator */
1540 >    final class ArrayListSpliterator implements Spliterator<E> {
1541 >
1542 >        /*
1543 >         * If ArrayLists were immutable, or structurally immutable (no
1544 >         * adds, removes, etc), we could implement their spliterators
1545 >         * with Arrays.spliterator. Instead we detect as much
1546 >         * interference during traversal as practical without
1547 >         * sacrificing much performance. We rely primarily on
1548 >         * modCounts. These are not guaranteed to detect concurrency
1549 >         * violations, and are sometimes overly conservative about
1550 >         * within-thread interference, but detect enough problems to
1551 >         * be worthwhile in practice. To carry this out, we (1) lazily
1552 >         * initialize fence and expectedModCount until the latest
1553 >         * point that we need to commit to the state we are checking
1554 >         * against; thus improving precision.  (This doesn't apply to
1555 >         * SubLists, that create spliterators with current non-lazy
1556 >         * values).  (2) We perform only a single
1557 >         * ConcurrentModificationException check at the end of forEach
1558 >         * (the most performance-sensitive method). When using forEach
1559 >         * (as opposed to iterators), we can normally only detect
1560 >         * interference after actions, not before. Further
1561 >         * CME-triggering checks apply to all other possible
1562 >         * violations of assumptions for example null or too-small
1563 >         * elementData array given its size(), that could only have
1564 >         * occurred due to interference.  This allows the inner loop
1565 >         * of forEach to run without any further checks, and
1566 >         * simplifies lambda-resolution. While this does entail a
1567 >         * number of checks, note that in the common case of
1568 >         * list.stream().forEach(a), no checks or other computation
1569 >         * occur anywhere other than inside forEach itself.  The other
1570 >         * less-often-used methods cannot take advantage of most of
1571 >         * these streamlinings.
1572 >         */
1573 >
1574 >        private int index; // current index, modified on advance/split
1575 >        private int fence; // -1 until used; then one past last index
1576 >        private int expectedModCount; // initialized when fence set
1577 >
1578 >        /** Creates new spliterator covering the given range. */
1579 >        ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1580 >            this.index = origin;
1581 >            this.fence = fence;
1582 >            this.expectedModCount = expectedModCount;
1583 >        }
1584 >
1585 >        private int getFence() { // initialize fence to size on first use
1586 >            int hi; // (a specialized variant appears in method forEach)
1587 >            if ((hi = fence) < 0) {
1588                  expectedModCount = modCount;
1589 <            } catch (IndexOutOfBoundsException ex) {
1590 <                throw new ConcurrentModificationException();
1591 <            }
1592 <        }
1589 >                hi = fence = size;
1590 >            }
1591 >            return hi;
1592 >        }
1593 >
1594 >        public ArrayListSpliterator trySplit() {
1595 >            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1596 >            return (lo >= mid) ? null : // divide range in half unless too small
1597 >                new ArrayListSpliterator(lo, index = mid, expectedModCount);
1598 >        }
1599 >
1600 >        public boolean tryAdvance(Consumer<? super E> action) {
1601 >            if (action == null)
1602 >                throw new NullPointerException();
1603 >            int hi = getFence(), i = index;
1604 >            if (i < hi) {
1605 >                index = i + 1;
1606 >                @SuppressWarnings("unchecked") E e = (E)elementData[i];
1607 >                action.accept(e);
1608 >                if (modCount != expectedModCount)
1609 >                    throw new ConcurrentModificationException();
1610 >                return true;
1611 >            }
1612 >            return false;
1613 >        }
1614 >
1615 >        public void forEachRemaining(Consumer<? super E> action) {
1616 >            int i, hi, mc; // hoist accesses and checks from loop
1617 >            Object[] a;
1618 >            if (action == null)
1619 >                throw new NullPointerException();
1620 >            if ((a = elementData) != null) {
1621 >                if ((hi = fence) < 0) {
1622 >                    mc = modCount;
1623 >                    hi = size;
1624 >                }
1625 >                else
1626 >                    mc = expectedModCount;
1627 >                if ((i = index) >= 0 && (index = hi) <= a.length) {
1628 >                    for (; i < hi; ++i) {
1629 >                        @SuppressWarnings("unchecked") E e = (E) a[i];
1630 >                        action.accept(e);
1631 >                    }
1632 >                    if (modCount == mc)
1633 >                        return;
1634 >                }
1635 >            }
1636 >            throw new ConcurrentModificationException();
1637 >        }
1638 >
1639 >        public long estimateSize() {
1640 >            return getFence() - index;
1641 >        }
1642 >
1643 >        public int characteristics() {
1644 >            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1645 >        }
1646 >    }
1647 >
1648 >    // A tiny bit set implementation
1649 >
1650 >    private static long[] nBits(int n) {
1651 >        return new long[((n - 1) >> 6) + 1];
1652 >    }
1653 >    private static void setBit(long[] bits, int i) {
1654 >        bits[i >> 6] |= 1L << i;
1655 >    }
1656 >    private static boolean isClear(long[] bits, int i) {
1657 >        return (bits[i >> 6] & (1L << i)) == 0;
1658 >    }
1659 >
1660 >    /**
1661 >     * @throws NullPointerException {@inheritDoc}
1662 >     */
1663 >    @Override
1664 >    public boolean removeIf(Predicate<? super E> filter) {
1665 >        return removeIf(filter, 0, size);
1666 >    }
1667 >
1668 >    /**
1669 >     * Removes all elements satisfying the given predicate, from index
1670 >     * i (inclusive) to index end (exclusive).
1671 >     */
1672 >    boolean removeIf(Predicate<? super E> filter, int i, final int end) {
1673 >        Objects.requireNonNull(filter);
1674 >        int expectedModCount = modCount;
1675 >        final Object[] es = elementData;
1676 >        // Optimize for initial run of survivors
1677 >        for (; i < end && !filter.test(elementAt(es, i)); i++)
1678 >            ;
1679 >        // Tolerate predicates that reentrantly access the collection for
1680 >        // read (but writers still get CME), so traverse once to find
1681 >        // elements to delete, a second pass to physically expunge.
1682 >        if (i < end) {
1683 >            final int beg = i;
1684 >            final long[] deathRow = nBits(end - beg);
1685 >            deathRow[0] = 1L;   // set bit 0
1686 >            for (i = beg + 1; i < end; i++)
1687 >                if (filter.test(elementAt(es, i)))
1688 >                    setBit(deathRow, i - beg);
1689 >            if (modCount != expectedModCount)
1690 >                throw new ConcurrentModificationException();
1691 >            modCount++;
1692 >            int w = beg;
1693 >            for (i = beg; i < end; i++)
1694 >                if (isClear(deathRow, i - beg))
1695 >                    es[w++] = es[i];
1696 >            shiftTailOverGap(es, w, end);
1697 >            // checkInvariants();
1698 >            return true;
1699 >        } else {
1700 >            if (modCount != expectedModCount)
1701 >                throw new ConcurrentModificationException();
1702 >            // checkInvariants();
1703 >            return false;
1704 >        }
1705 >    }
1706 >
1707 >    @Override
1708 >    public void replaceAll(UnaryOperator<E> operator) {
1709 >        replaceAllRange(operator, 0, size);
1710 >        // TODO(8203662): remove increment of modCount from ...
1711 >        modCount++;
1712 >    }
1713 >
1714 >    private void replaceAllRange(UnaryOperator<E> operator, int i, int end) {
1715 >        Objects.requireNonNull(operator);
1716 >        final int expectedModCount = modCount;
1717 >        final Object[] es = elementData;
1718 >        for (; modCount == expectedModCount && i < end; i++)
1719 >            es[i] = operator.apply(elementAt(es, i));
1720 >        if (modCount != expectedModCount)
1721 >            throw new ConcurrentModificationException();
1722 >        // checkInvariants();
1723 >    }
1724 >
1725 >    @Override
1726 >    @SuppressWarnings("unchecked")
1727 >    public void sort(Comparator<? super E> c) {
1728 >        final int expectedModCount = modCount;
1729 >        Arrays.sort((E[]) elementData, 0, size, c);
1730 >        if (modCount != expectedModCount)
1731 >            throw new ConcurrentModificationException();
1732 >        modCount++;
1733 >        // checkInvariants();
1734 >    }
1735 >
1736 >    void checkInvariants() {
1737 >        // assert size >= 0;
1738 >        // assert size == elementData.length || elementData[size] == null;
1739      }
1740   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines