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.27 by jsr166, Sun May 18 23:59:57 2008 UTC vs.
Revision 1.69 by jsr166, Fri Aug 30 18:05:39 2019 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright 1997-2007 Sun Microsystems, Inc.  All Rights Reserved.
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   * 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 + // 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.)
40 > * {@code Vector}, except that it is unsynchronized.)
41   *
42 < * <p>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.
47 > * to that for the {@code LinkedList} implementation.
48   *
49 < * <p>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.
55   *
56 < * <p>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 66 | Line 72 | package java.util;
72   * unsynchronized access to the list:<pre>
73   *   List list = Collections.synchronizedList(new ArrayList(...));</pre>
74   *
75 < * <p><a name="fail-fast"/>
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
# Line 87 | Line 93 | package java.util;
93   * should be used only to detect bugs.</i>
94   *
95   * <p>This class is a member of the
96 < * <a href="{@docRoot}/../technotes/guides/collections/index.html">
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   * @see     Collection
# Line 98 | Line 106 | package java.util;
106   * @see     Vector
107   * @since   1.2
108   */
101
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 120 | 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
151 <     * @exception IllegalArgumentException if the specified initial capacity
152 <     *            is negative
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      /**
# Line 149 | Line 179 | public class ArrayList<E> extends Abstra
179       */
180      public ArrayList(Collection<? extends E> c) {
181          elementData = c.toArray();
182 <        size = elementData.length;
183 <        // c.toArray might (incorrectly) not return Object[] (see 6260652)
184 <        if (elementData.getClass() != Object[].class)
185 <            elementData = Arrays.copyOf(elementData, size, Object[].class);
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  
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);
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
212 >     * @param minCapacity the desired minimum capacity
213       */
214      public void ensureCapacity(int minCapacity) {
215 <        modCount++;
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 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 Object[] grow(int minCapacity) {
231          int oldCapacity = elementData.length;
232 <        if (minCapacity > oldCapacity) {
233 <            Object oldData[] = elementData;
234 <            int newCapacity = (oldCapacity * 3)/2 + 1;
235 <            if (newCapacity < minCapacity)
236 <                newCapacity = minCapacity;
237 <            // minCapacity is usually close to size, so this is a win:
238 <            elementData = Arrays.copyOf(elementData, newCapacity);
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      /**
247       * Returns the number of elements in this list.
248       *
# Line 198 | Line 253 | public class ArrayList<E> extends Abstra
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;
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;
# Line 222 | Line 277 | public class ArrayList<E> extends Abstra
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 +        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 = 0; i < size; i++)
292 <                if (elementData[i]==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 = 0; i < size; i++)
298 <                if (o.equals(elementData[i]))
297 >            for (int i = start; i < end; i++) {
298 >                if (o.equals(es[i])) {
299                      return i;
300 +                }
301 +            }
302          }
303          return -1;
304      }
# Line 242 | Line 306 | public class ArrayList<E> extends Abstra
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 +        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 = size-1; i >= 0; i--)
321 <                if (elementData[i]==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 = size-1; i >= 0; i--)
327 <                if (o.equals(elementData[i]))
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 <            @SuppressWarnings("unchecked")
271 <                ArrayList<E> v = (ArrayList<E>) super.clone();
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();
349 >            throw new InternalError(e);
350          }
351      }
352  
# Line 307 | 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 338 | Line 410 | public class ArrayList<E> extends Abstra
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      /**
419       * Returns the element at the specified position in this list.
420       *
# Line 346 | Line 423 | public class ArrayList<E> extends Abstra
423       * @throws IndexOutOfBoundsException {@inheritDoc}
424       */
425      public E get(int index) {
426 <        rangeCheck(index);
350 <
426 >        Objects.checkIndex(index, size);
427          return elementData(index);
428      }
429  
# Line 361 | Line 437 | public class ArrayList<E> extends Abstra
437       * @throws IndexOutOfBoundsException {@inheritDoc}
438       */
439      public E set(int index, E element) {
440 <        rangeCheck(index);
365 <
440 >        Objects.checkIndex(index, size);
441          E oldValue = elementData(index);
442          elementData[index] = element;
443          return oldValue;
444      }
445  
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 <        ensureCapacity(size + 1);  // Increments modCount!!
466 <        elementData[size++] = e;
465 >        modCount++;
466 >        add(e, elementData, size);
467          return true;
468      }
469  
# Line 391 | Line 478 | public class ArrayList<E> extends Abstra
478       */
479      public void add(int index, E element) {
480          rangeCheckForAdd(index);
481 <
482 <        ensureCapacity(size+1);  // Increments modCount!!
483 <        System.arraycopy(elementData, index, elementData, index + 1,
484 <                         size - index);
481 >        modCount++;
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++;
490 >        size = s + 1;
491 >        // checkInvariants();
492      }
493  
494      /**
# Line 409 | Line 501 | public class ArrayList<E> extends Abstra
501       * @throws IndexOutOfBoundsException {@inheritDoc}
502       */
503      public E remove(int index) {
504 <        rangeCheck(index);
505 <
414 <        modCount++;
415 <        E oldValue = elementData(index);
504 >        Objects.checkIndex(index, size);
505 >        final Object[] es = elementData;
506  
507 <        int numMoved = size - index - 1;
508 <        if (numMoved > 0)
419 <            System.arraycopy(elementData, index+1, elementData, index,
420 <                             numMoved);
421 <        elementData[--size] = null; // Let gc do its work
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);
466 <        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 472 | Line 649 | public class ArrayList<E> extends Abstra
649       */
650      public void clear() {
651          modCount++;
652 <
653 <        // Let gc do its work
654 <        for (int i = 0; i < size; i++)
478 <            elementData[i] = null;
479 <
480 <        size = 0;
652 >        final Object[] es = elementData;
653 >        for (int to = size, i = size = 0; i < to; i++)
654 >            es[i] = null;
655      }
656  
657      /**
# Line 490 | 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();
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 513 | 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       */
# Line 521 | Line 702 | public class ArrayList<E> extends Abstra
702          rangeCheckForAdd(index);
703  
704          Object[] a = c.toArray();
705 +        modCount++;
706          int numNew = a.length;
707 <        ensureCapacity(size + numNew);  // Increments modCount
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 = size - index;
714 >        int numMoved = s - index;
715          if (numMoved > 0)
716 <            System.arraycopy(elementData, index, elementData, index + numNew,
716 >            System.arraycopy(elementData, index,
717 >                             elementData, index + numNew,
718                               numMoved);
531
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      /**
# Line 544 | Line 732 | public class ArrayList<E> extends Abstra
732       * @throws IndexOutOfBoundsException if {@code fromIndex} or
733       *         {@code toIndex} is out of range
734       *         ({@code fromIndex < 0 ||
547     *          fromIndex >= size() ||
735       *          toIndex > size() ||
736       *          toIndex < fromIndex})
737       */
738      protected void removeRange(int fromIndex, int toIndex) {
739 +        if (fromIndex > toIndex) {
740 +            throw new IndexOutOfBoundsException(
741 +                    outOfBoundsMsg(fromIndex, toIndex));
742 +        }
743          modCount++;
744 <        int numMoved = size - toIndex;
745 <        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;
744 >        shiftTailOverGap(elementData, fromIndex, toIndex);
745 >        // checkInvariants();
746      }
747  
748 <    /**
749 <     * Checks if the given index is in range.  If not, throws an appropriate
750 <     * runtime exception.  This method does *not* check if the index is
751 <     * negative: It is always used immediately prior to an array access,
752 <     * 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));
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      /**
# Line 589 | Line 770 | public class ArrayList<E> extends Abstra
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       * @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 (optional)
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 (optional),
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);
795 >        return batchRemove(c, false, 0, size);
796      }
797  
798      /**
# Line 613 | Line 803 | public class ArrayList<E> extends Abstra
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 (optional)
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 (optional),
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);
815 >        return batchRemove(c, true, 0, size);
816      }
817  
818 <    private boolean batchRemove(Collection<?> c, boolean complement) {
819 <        final Object[] elementData = this.elementData;
820 <        int r = 0, w = 0;
821 <        boolean modified = false;
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 (; r < size; r++)
833 <                if (c.contains(elementData[r]) == complement)
834 <                    elementData[w++] = elementData[r];
835 <        } finally {
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 <            if (r != size) {
839 <                System.arraycopy(elementData, r,
840 <                                 elementData, w,
841 <                                 size - r);
842 <                w += size - r;
843 <            }
643 <            if (w != size) {
644 <                for (int i = w; i < size; i++)
645 <                    elementData[i] = null;
646 <                modCount += size - w;
647 <                size = w;
648 <                modified = true;
649 <            }
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 <        return modified;
845 >        // checkInvariants();
846 >        return true;
847      }
848  
849      /**
850 <     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
851 <     * is, serialize it).
850 >     * Saves the state of the {@code ArrayList} instance to a stream
851 >     * (that is, serializes it).
852       *
853 <     * @serialData The length of the array backing the <tt>ArrayList</tt>
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{
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++)
870 >        for (int i=0; i<size; i++) {
871              s.writeObject(elementData[i]);
872 +        }
873  
874          if (modCount != expectedModCount) {
875              throw new ConcurrentModificationException();
876          }
678
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 {
890 +
891          // Read in size, and any hidden stuff
892          s.defaultReadObject();
893  
894 <        // Read in array length and allocate array
895 <        int arrayLength = s.readInt();
896 <        Object[] a = elementData = new Object[arrayLength];
897 <
898 <        // Read in all elements in the proper order.
899 <        for (int i=0; i<size; i++)
900 <            a[i] = s.readObject();
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      /**
# Line 709 | Line 925 | public class ArrayList<E> extends Abstra
925       * @throws IndexOutOfBoundsException {@inheritDoc}
926       */
927      public ListIterator<E> listIterator(int index) {
928 <        if (index < 0 || index > size)
713 <            throw new IndexOutOfBoundsException("Index: "+index);
928 >        rangeCheckForAdd(index);
929          return new ListItr(index);
930      }
931  
# Line 745 | Line 960 | public class ArrayList<E> extends Abstra
960          int lastRet = -1; // index of last element returned; -1 if no such
961          int expectedModCount = modCount;
962  
963 +        // prevent creating a synthetic constructor
964 +        Itr() {}
965 +
966          public boolean hasNext() {
967              return cursor != size;
968          }
# Line 777 | Line 995 | public class ArrayList<E> extends Abstra
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 +        }
1015 +
1016          final void checkForComodification() {
1017              if (modCount != expectedModCount)
1018                  throw new ConcurrentModificationException();
# Line 875 | Line 1111 | public class ArrayList<E> extends Abstra
1111       */
1112      public List<E> subList(int fromIndex, int toIndex) {
1113          subListRangeCheck(fromIndex, toIndex, size);
1114 <        return new SubList(this, 0, fromIndex, toIndex);
1114 >        return new SubList<>(this, fromIndex, toIndex);
1115      }
1116  
1117 <    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
1118 <        if (fromIndex < 0)
1119 <            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;
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 <        SubList(AbstractList<E> parent,
1124 <                int offset, int fromIndex, int toIndex) {
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.parentOffset = fromIndex;
901 <            this.offset = offset + fromIndex;
1140 >            this.offset = parent.offset + fromIndex;
1141              this.size = toIndex - fromIndex;
1142 <            this.modCount = ArrayList.this.modCount;
1142 >            this.modCount = root.modCount;
1143          }
1144  
1145 <        public E set(int index, E e) {
1146 <            rangeCheck(index);
1145 >        public E set(int index, E element) {
1146 >            Objects.checkIndex(index, size);
1147              checkForComodification();
1148 <            E oldValue = ArrayList.this.elementData(offset + index);
1149 <            ArrayList.this.elementData[offset + index] = e;
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 <            rangeCheck(index);
1154 >            Objects.checkIndex(index, size);
1155              checkForComodification();
1156 <            return ArrayList.this.elementData(offset + index);
1156 >            return root.elementData(offset + index);
1157          }
1158  
1159          public int size() {
1160              checkForComodification();
1161 <            return this.size;
1161 >            return size;
1162          }
1163  
1164 <        public void add(int index, E e) {
1164 >        public void add(int index, E element) {
1165              rangeCheckForAdd(index);
1166              checkForComodification();
1167 <            parent.add(parentOffset + index, e);
1168 <            this.modCount = parent.modCount;
930 <            this.size++;
1167 >            root.add(offset + index, element);
1168 >            updateSizeAndModCount(1);
1169          }
1170  
1171          public E remove(int index) {
1172 <            rangeCheck(index);
1172 >            Objects.checkIndex(index, size);
1173              checkForComodification();
1174 <            E result = parent.remove(parentOffset + index);
1175 <            this.modCount = parent.modCount;
938 <            this.size--;
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 <            parent.removeRange(parentOffset + fromIndex,
1182 <                               parentOffset + toIndex);
946 <            this.modCount = parent.modCount;
947 <            this.size -= toIndex - fromIndex;
1181 >            root.removeRange(offset + fromIndex, offset + toIndex);
1182 >            updateSizeAndModCount(fromIndex - toIndex);
1183          }
1184  
1185          public boolean addAll(Collection<? extends E> c) {
# Line 956 | Line 1191 | public class ArrayList<E> extends Abstra
1191              int cSize = c.size();
1192              if (cSize==0)
1193                  return false;
959
1194              checkForComodification();
1195 <            parent.addAll(parentOffset + index, c);
1196 <            this.modCount = parent.modCount;
963 <            this.size += cSize;
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 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(final int index) {
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 = ArrayList.this.modCount;
1295 >                int expectedModCount = root.modCount;
1296  
1297                  public boolean hasNext() {
1298                      return cursor != SubList.this.size;
# Line 987 | Line 1304 | public class ArrayList<E> extends Abstra
1304                      int i = cursor;
1305                      if (i >= SubList.this.size)
1306                          throw new NoSuchElementException();
1307 <                    Object[] elementData = ArrayList.this.elementData;
1307 >                    Object[] elementData = root.elementData;
1308                      if (offset + i >= elementData.length)
1309                          throw new ConcurrentModificationException();
1310                      cursor = i + 1;
# Line 1004 | Line 1321 | public class ArrayList<E> extends Abstra
1321                      int i = cursor - 1;
1322                      if (i < 0)
1323                          throw new NoSuchElementException();
1324 <                    Object[] elementData = ArrayList.this.elementData;
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 && 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                  }
# Line 1028 | Line 1362 | public class ArrayList<E> extends Abstra
1362                          SubList.this.remove(lastRet);
1363                          cursor = lastRet;
1364                          lastRet = -1;
1365 <                        expectedModCount = ArrayList.this.modCount;
1365 >                        expectedModCount = root.modCount;
1366                      } catch (IndexOutOfBoundsException ex) {
1367                          throw new ConcurrentModificationException();
1368                      }
# Line 1040 | Line 1374 | public class ArrayList<E> extends Abstra
1374                      checkForComodification();
1375  
1376                      try {
1377 <                        ArrayList.this.set(offset + lastRet, e);
1377 >                        root.set(offset + lastRet, e);
1378                      } catch (IndexOutOfBoundsException ex) {
1379                          throw new ConcurrentModificationException();
1380                      }
# Line 1054 | Line 1388 | public class ArrayList<E> extends Abstra
1388                          SubList.this.add(i, e);
1389                          cursor = i + 1;
1390                          lastRet = -1;
1391 <                        expectedModCount = ArrayList.this.modCount;
1391 >                        expectedModCount = root.modCount;
1392                      } catch (IndexOutOfBoundsException ex) {
1393                          throw new ConcurrentModificationException();
1394                      }
1395                  }
1396  
1397                  final void checkForComodification() {
1398 <                    if (expectedModCount != ArrayList.this.modCount)
1398 >                    if (root.modCount != expectedModCount)
1399                          throw new ConcurrentModificationException();
1400                  }
1401              };
# Line 1069 | Line 1403 | public class ArrayList<E> extends Abstra
1403  
1404          public List<E> subList(int fromIndex, int toIndex) {
1405              subListRangeCheck(fromIndex, toIndex, size);
1406 <            return new SubList(this, offset, fromIndex, toIndex);
1073 <        }
1074 <
1075 <        private void rangeCheck(int index) {
1076 <            if (index < 0 || index >= this.size)
1077 <                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
1406 >            return new SubList<>(this, fromIndex, toIndex);
1407          }
1408  
1409          private void rangeCheckForAdd(int index) {
# Line 1087 | Line 1416 | public class ArrayList<E> extends Abstra
1416          }
1417  
1418          private void checkForComodification() {
1419 <            if (ArrayList.this.modCount != this.modCount)
1419 >            if (root.modCount != modCount)
1420                  throw new ConcurrentModificationException();
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 +                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