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.30 by jsr166, Sun Sep 5 21:32:19 2010 UTC vs.
Revision 1.71 by jsr166, Fri Jul 24 20:57:26 2020 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright (c) 1997, 2008, Oracle and/or its affiliates. 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 25 | Line 25
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 148 | Line 178 | public class ArrayList<E> extends Abstra
178       * @throws NullPointerException if the specified collection is null
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);
181 >        Object[] a = c.toArray();
182 >        if ((size = a.length) != 0) {
183 >            if (c.getClass() == ArrayList.class) {
184 >                elementData = a;
185 >            } else {
186 >                elementData = Arrays.copyOf(a, size, Object[].class);
187 >            }
188 >        } else {
189 >            // replace with empty array.
190 >            elementData = EMPTY_ELEMENTDATA;
191 >        }
192      }
193  
194      /**
195 <     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
195 >     * Trims the capacity of this {@code ArrayList} instance to be the
196       * list's current size.  An application can use this operation to minimize
197 <     * the storage of an <tt>ArrayList</tt> instance.
197 >     * the storage of an {@code ArrayList} instance.
198       */
199      public void trimToSize() {
200          modCount++;
201 <        int oldCapacity = elementData.length;
202 <        if (size < oldCapacity) {
203 <            elementData = Arrays.copyOf(elementData, size);
201 >        if (size < elementData.length) {
202 >            elementData = (size == 0)
203 >              ? EMPTY_ELEMENTDATA
204 >              : Arrays.copyOf(elementData, size);
205          }
206      }
207  
208      /**
209 <     * Increases the capacity of this <tt>ArrayList</tt> instance, if
209 >     * Increases the capacity of this {@code ArrayList} instance, if
210       * necessary, to ensure that it can hold at least the number of elements
211       * specified by the minimum capacity argument.
212       *
213 <     * @param   minCapacity   the desired minimum capacity
213 >     * @param minCapacity the desired minimum capacity
214       */
215      public void ensureCapacity(int minCapacity) {
216 <        modCount++;
216 >        if (minCapacity > elementData.length
217 >            && !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
218 >                 && minCapacity <= DEFAULT_CAPACITY)) {
219 >            modCount++;
220 >            grow(minCapacity);
221 >        }
222 >    }
223 >
224 >    /**
225 >     * Increases the capacity to ensure that it can hold at least the
226 >     * number of elements specified by the minimum capacity argument.
227 >     *
228 >     * @param minCapacity the desired minimum capacity
229 >     * @throws OutOfMemoryError if minCapacity is less than zero
230 >     */
231 >    private Object[] grow(int minCapacity) {
232          int oldCapacity = elementData.length;
233 <        if (minCapacity > oldCapacity) {
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);
233 >        if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
234 >            int newCapacity = ArraysSupport.newLength(oldCapacity,
235 >                    minCapacity - oldCapacity, /* minimum growth */
236 >                    oldCapacity >> 1           /* preferred growth */);
237 >            return elementData = Arrays.copyOf(elementData, newCapacity);
238 >        } else {
239 >            return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];
240          }
241      }
242  
243 +    private Object[] grow() {
244 +        return grow(size + 1);
245 +    }
246 +
247      /**
248       * Returns the number of elements in this list.
249       *
# Line 197 | Line 254 | public class ArrayList<E> extends Abstra
254      }
255  
256      /**
257 <     * Returns <tt>true</tt> if this list contains no elements.
257 >     * Returns {@code true} if this list contains no elements.
258       *
259 <     * @return <tt>true</tt> if this list contains no elements
259 >     * @return {@code true} if this list contains no elements
260       */
261      public boolean isEmpty() {
262          return size == 0;
263      }
264  
265      /**
266 <     * Returns <tt>true</tt> if this list contains the specified element.
267 <     * More formally, returns <tt>true</tt> if and only if this list contains
268 <     * at least one element <tt>e</tt> such that
269 <     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
266 >     * Returns {@code true} if this list contains the specified element.
267 >     * More formally, returns {@code true} if and only if this list contains
268 >     * at least one element {@code e} such that
269 >     * {@code Objects.equals(o, e)}.
270       *
271       * @param o element whose presence in this list is to be tested
272 <     * @return <tt>true</tt> if this list contains the specified element
272 >     * @return {@code true} if this list contains the specified element
273       */
274      public boolean contains(Object o) {
275          return indexOf(o) >= 0;
# Line 221 | Line 278 | public class ArrayList<E> extends Abstra
278      /**
279       * Returns the index of the first occurrence of the specified element
280       * in this list, or -1 if this list does not contain the element.
281 <     * More formally, returns the lowest index <tt>i</tt> such that
282 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
281 >     * More formally, returns the lowest index {@code i} such that
282 >     * {@code Objects.equals(o, get(i))},
283       * or -1 if there is no such index.
284       */
285      public int indexOf(Object o) {
286 +        return indexOfRange(o, 0, size);
287 +    }
288 +
289 +    int indexOfRange(Object o, int start, int end) {
290 +        Object[] es = elementData;
291          if (o == null) {
292 <            for (int i = 0; i < size; i++)
293 <                if (elementData[i]==null)
292 >            for (int i = start; i < end; i++) {
293 >                if (es[i] == null) {
294                      return i;
295 +                }
296 +            }
297          } else {
298 <            for (int i = 0; i < size; i++)
299 <                if (o.equals(elementData[i]))
298 >            for (int i = start; i < end; i++) {
299 >                if (o.equals(es[i])) {
300                      return i;
301 +                }
302 +            }
303          }
304          return -1;
305      }
# Line 241 | Line 307 | public class ArrayList<E> extends Abstra
307      /**
308       * Returns the index of the last occurrence of the specified element
309       * in this list, or -1 if this list does not contain the element.
310 <     * More formally, returns the highest index <tt>i</tt> such that
311 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
310 >     * More formally, returns the highest index {@code i} such that
311 >     * {@code Objects.equals(o, get(i))},
312       * or -1 if there is no such index.
313       */
314      public int lastIndexOf(Object o) {
315 +        return lastIndexOfRange(o, 0, size);
316 +    }
317 +
318 +    int lastIndexOfRange(Object o, int start, int end) {
319 +        Object[] es = elementData;
320          if (o == null) {
321 <            for (int i = size-1; i >= 0; i--)
322 <                if (elementData[i]==null)
321 >            for (int i = end - 1; i >= start; i--) {
322 >                if (es[i] == null) {
323                      return i;
324 +                }
325 +            }
326          } else {
327 <            for (int i = size-1; i >= 0; i--)
328 <                if (o.equals(elementData[i]))
327 >            for (int i = end - 1; i >= start; i--) {
328 >                if (o.equals(es[i])) {
329                      return i;
330 +                }
331 +            }
332          }
333          return -1;
334      }
335  
336      /**
337 <     * Returns a shallow copy of this <tt>ArrayList</tt> instance.  (The
337 >     * Returns a shallow copy of this {@code ArrayList} instance.  (The
338       * elements themselves are not copied.)
339       *
340 <     * @return a clone of this <tt>ArrayList</tt> instance
340 >     * @return a clone of this {@code ArrayList} instance
341       */
342      public Object clone() {
343          try {
344 <            @SuppressWarnings("unchecked")
270 <                ArrayList<E> v = (ArrayList<E>) super.clone();
344 >            ArrayList<?> v = (ArrayList<?>) super.clone();
345              v.elementData = Arrays.copyOf(elementData, size);
346              v.modCount = 0;
347              return v;
348          } catch (CloneNotSupportedException e) {
349              // this shouldn't happen, since we are Cloneable
350 <            throw new InternalError();
350 >            throw new InternalError(e);
351          }
352      }
353  
# Line 306 | Line 380 | public class ArrayList<E> extends Abstra
380       * <p>If the list fits in the specified array with room to spare
381       * (i.e., the array has more elements than the list), the element in
382       * the array immediately following the end of the collection is set to
383 <     * <tt>null</tt>.  (This is useful in determining the length of the
383 >     * {@code null}.  (This is useful in determining the length of the
384       * list <i>only</i> if the caller knows that the list does not contain
385       * any null elements.)
386       *
# Line 337 | Line 411 | public class ArrayList<E> extends Abstra
411          return (E) elementData[index];
412      }
413  
414 +    @SuppressWarnings("unchecked")
415 +    static <E> E elementAt(Object[] es, int index) {
416 +        return (E) es[index];
417 +    }
418 +
419      /**
420       * Returns the element at the specified position in this list.
421       *
# Line 345 | Line 424 | public class ArrayList<E> extends Abstra
424       * @throws IndexOutOfBoundsException {@inheritDoc}
425       */
426      public E get(int index) {
427 <        rangeCheck(index);
349 <
427 >        Objects.checkIndex(index, size);
428          return elementData(index);
429      }
430  
# Line 360 | Line 438 | public class ArrayList<E> extends Abstra
438       * @throws IndexOutOfBoundsException {@inheritDoc}
439       */
440      public E set(int index, E element) {
441 <        rangeCheck(index);
364 <
441 >        Objects.checkIndex(index, size);
442          E oldValue = elementData(index);
443          elementData[index] = element;
444          return oldValue;
445      }
446  
447      /**
448 +     * This helper method split out from add(E) to keep method
449 +     * bytecode size under 35 (the -XX:MaxInlineSize default value),
450 +     * which helps when add(E) is called in a C1-compiled loop.
451 +     */
452 +    private void add(E e, Object[] elementData, int s) {
453 +        if (s == elementData.length)
454 +            elementData = grow();
455 +        elementData[s] = e;
456 +        size = s + 1;
457 +    }
458 +
459 +    /**
460       * Appends the specified element to the end of this list.
461       *
462       * @param e element to be appended to this list
463 <     * @return <tt>true</tt> (as specified by {@link Collection#add})
463 >     * @return {@code true} (as specified by {@link Collection#add})
464       */
465      public boolean add(E e) {
466 <        ensureCapacity(size + 1);  // Increments modCount!!
467 <        elementData[size++] = e;
466 >        modCount++;
467 >        add(e, elementData, size);
468          return true;
469      }
470  
# Line 390 | Line 479 | public class ArrayList<E> extends Abstra
479       */
480      public void add(int index, E element) {
481          rangeCheckForAdd(index);
482 <
483 <        ensureCapacity(size+1);  // Increments modCount!!
484 <        System.arraycopy(elementData, index, elementData, index + 1,
485 <                         size - index);
482 >        modCount++;
483 >        final int s;
484 >        Object[] elementData;
485 >        if ((s = size) == (elementData = this.elementData).length)
486 >            elementData = grow();
487 >        System.arraycopy(elementData, index,
488 >                         elementData, index + 1,
489 >                         s - index);
490          elementData[index] = element;
491 <        size++;
491 >        size = s + 1;
492 >        // checkInvariants();
493      }
494  
495      /**
# Line 408 | Line 502 | public class ArrayList<E> extends Abstra
502       * @throws IndexOutOfBoundsException {@inheritDoc}
503       */
504      public E remove(int index) {
505 <        rangeCheck(index);
505 >        Objects.checkIndex(index, size);
506 >        final Object[] es = elementData;
507  
508 <        modCount++;
509 <        E oldValue = elementData(index);
415 <
416 <        int numMoved = size - index - 1;
417 <        if (numMoved > 0)
418 <            System.arraycopy(elementData, index+1, elementData, index,
419 <                             numMoved);
420 <        elementData[--size] = null; // Let gc do its work
508 >        @SuppressWarnings("unchecked") E oldValue = (E) es[index];
509 >        fastRemove(es, index);
510  
511 +        // checkInvariants();
512          return oldValue;
513      }
514  
515      /**
516 +     * {@inheritDoc}
517 +     */
518 +    public boolean equals(Object o) {
519 +        if (o == this) {
520 +            return true;
521 +        }
522 +
523 +        if (!(o instanceof List)) {
524 +            return false;
525 +        }
526 +
527 +        final int expectedModCount = modCount;
528 +        // ArrayList can be subclassed and given arbitrary behavior, but we can
529 +        // still deal with the common case where o is ArrayList precisely
530 +        boolean equal = (o.getClass() == ArrayList.class)
531 +            ? equalsArrayList((ArrayList<?>) o)
532 +            : equalsRange((List<?>) o, 0, size);
533 +
534 +        checkForComodification(expectedModCount);
535 +        return equal;
536 +    }
537 +
538 +    boolean equalsRange(List<?> other, int from, int to) {
539 +        final Object[] es = elementData;
540 +        if (to > es.length) {
541 +            throw new ConcurrentModificationException();
542 +        }
543 +        var oit = other.iterator();
544 +        for (; from < to; from++) {
545 +            if (!oit.hasNext() || !Objects.equals(es[from], oit.next())) {
546 +                return false;
547 +            }
548 +        }
549 +        return !oit.hasNext();
550 +    }
551 +
552 +    private boolean equalsArrayList(ArrayList<?> other) {
553 +        final int otherModCount = other.modCount;
554 +        final int s = size;
555 +        boolean equal;
556 +        if (equal = (s == other.size)) {
557 +            final Object[] otherEs = other.elementData;
558 +            final Object[] es = elementData;
559 +            if (s > es.length || s > otherEs.length) {
560 +                throw new ConcurrentModificationException();
561 +            }
562 +            for (int i = 0; i < s; i++) {
563 +                if (!Objects.equals(es[i], otherEs[i])) {
564 +                    equal = false;
565 +                    break;
566 +                }
567 +            }
568 +        }
569 +        other.checkForComodification(otherModCount);
570 +        return equal;
571 +    }
572 +
573 +    private void checkForComodification(final int expectedModCount) {
574 +        if (modCount != expectedModCount) {
575 +            throw new ConcurrentModificationException();
576 +        }
577 +    }
578 +
579 +    /**
580 +     * {@inheritDoc}
581 +     */
582 +    public int hashCode() {
583 +        int expectedModCount = modCount;
584 +        int hash = hashCodeRange(0, size);
585 +        checkForComodification(expectedModCount);
586 +        return hash;
587 +    }
588 +
589 +    int hashCodeRange(int from, int to) {
590 +        final Object[] es = elementData;
591 +        if (to > es.length) {
592 +            throw new ConcurrentModificationException();
593 +        }
594 +        int hashCode = 1;
595 +        for (int i = from; i < to; i++) {
596 +            Object e = es[i];
597 +            hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());
598 +        }
599 +        return hashCode;
600 +    }
601 +
602 +    /**
603       * Removes the first occurrence of the specified element from this list,
604       * if it is present.  If the list does not contain the element, it is
605       * unchanged.  More formally, removes the element with the lowest index
606 <     * <tt>i</tt> such that
607 <     * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
608 <     * (if such an element exists).  Returns <tt>true</tt> if this list
606 >     * {@code i} such that
607 >     * {@code Objects.equals(o, get(i))}
608 >     * (if such an element exists).  Returns {@code true} if this list
609       * contained the specified element (or equivalently, if this list
610       * changed as a result of the call).
611       *
612       * @param o element to be removed from this list, if present
613 <     * @return <tt>true</tt> if this list contained the specified element
613 >     * @return {@code true} if this list contained the specified element
614       */
615      public boolean remove(Object o) {
616 <        if (o == null) {
617 <            for (int index = 0; index < size; index++)
618 <                if (elementData[index] == null) {
619 <                    fastRemove(index);
620 <                    return true;
621 <                }
622 <        } else {
623 <            for (int index = 0; index < size; index++)
624 <                if (o.equals(elementData[index])) {
625 <                    fastRemove(index);
626 <                    return true;
627 <                }
616 >        final Object[] es = elementData;
617 >        final int size = this.size;
618 >        int i = 0;
619 >        found: {
620 >            if (o == null) {
621 >                for (; i < size; i++)
622 >                    if (es[i] == null)
623 >                        break found;
624 >            } else {
625 >                for (; i < size; i++)
626 >                    if (o.equals(es[i]))
627 >                        break found;
628 >            }
629 >            return false;
630          }
631 <        return false;
631 >        fastRemove(es, i);
632 >        return true;
633      }
634  
635 <    /*
635 >    /**
636       * Private remove method that skips bounds checking and does not
637       * return the value removed.
638       */
639 <    private void fastRemove(int index) {
639 >    private void fastRemove(Object[] es, int i) {
640          modCount++;
641 <        int numMoved = size - index - 1;
642 <        if (numMoved > 0)
643 <            System.arraycopy(elementData, index+1, elementData, index,
644 <                             numMoved);
465 <        elementData[--size] = null; // Let gc do its work
641 >        final int newSize;
642 >        if ((newSize = size - 1) > i)
643 >            System.arraycopy(es, i + 1, es, i, newSize - i);
644 >        es[size = newSize] = null;
645      }
646  
647      /**
# Line 471 | Line 650 | public class ArrayList<E> extends Abstra
650       */
651      public void clear() {
652          modCount++;
653 <
654 <        // Let gc do its work
655 <        for (int i = 0; i < size; i++)
477 <            elementData[i] = null;
478 <
479 <        size = 0;
653 >        final Object[] es = elementData;
654 >        for (int to = size, i = size = 0; i < to; i++)
655 >            es[i] = null;
656      }
657  
658      /**
# Line 489 | Line 665 | public class ArrayList<E> extends Abstra
665       * list is nonempty.)
666       *
667       * @param c collection containing elements to be added to this list
668 <     * @return <tt>true</tt> if this list changed as a result of the call
668 >     * @return {@code true} if this list changed as a result of the call
669       * @throws NullPointerException if the specified collection is null
670       */
671      public boolean addAll(Collection<? extends E> c) {
672          Object[] a = c.toArray();
673 +        modCount++;
674          int numNew = a.length;
675 <        ensureCapacity(size + numNew);  // Increments modCount
676 <        System.arraycopy(a, 0, elementData, size, numNew);
677 <        size += numNew;
678 <        return numNew != 0;
675 >        if (numNew == 0)
676 >            return false;
677 >        Object[] elementData;
678 >        final int s;
679 >        if (numNew > (elementData = this.elementData).length - (s = size))
680 >            elementData = grow(s + numNew);
681 >        System.arraycopy(a, 0, elementData, s, numNew);
682 >        size = s + numNew;
683 >        // checkInvariants();
684 >        return true;
685      }
686  
687      /**
# Line 512 | Line 695 | public class ArrayList<E> extends Abstra
695       * @param index index at which to insert the first element from the
696       *              specified collection
697       * @param c collection containing elements to be added to this list
698 <     * @return <tt>true</tt> if this list changed as a result of the call
698 >     * @return {@code true} if this list changed as a result of the call
699       * @throws IndexOutOfBoundsException {@inheritDoc}
700       * @throws NullPointerException if the specified collection is null
701       */
# Line 520 | Line 703 | public class ArrayList<E> extends Abstra
703          rangeCheckForAdd(index);
704  
705          Object[] a = c.toArray();
706 +        modCount++;
707          int numNew = a.length;
708 <        ensureCapacity(size + numNew);  // Increments modCount
708 >        if (numNew == 0)
709 >            return false;
710 >        Object[] elementData;
711 >        final int s;
712 >        if (numNew > (elementData = this.elementData).length - (s = size))
713 >            elementData = grow(s + numNew);
714  
715 <        int numMoved = size - index;
715 >        int numMoved = s - index;
716          if (numMoved > 0)
717 <            System.arraycopy(elementData, index, elementData, index + numNew,
717 >            System.arraycopy(elementData, index,
718 >                             elementData, index + numNew,
719                               numMoved);
530
720          System.arraycopy(a, 0, elementData, index, numNew);
721 <        size += numNew;
722 <        return numNew != 0;
721 >        size = s + numNew;
722 >        // checkInvariants();
723 >        return true;
724      }
725  
726      /**
# Line 543 | Line 733 | public class ArrayList<E> extends Abstra
733       * @throws IndexOutOfBoundsException if {@code fromIndex} or
734       *         {@code toIndex} is out of range
735       *         ({@code fromIndex < 0 ||
546     *          fromIndex >= size() ||
736       *          toIndex > size() ||
737       *          toIndex < fromIndex})
738       */
739      protected void removeRange(int fromIndex, int toIndex) {
740 +        if (fromIndex > toIndex) {
741 +            throw new IndexOutOfBoundsException(
742 +                    outOfBoundsMsg(fromIndex, toIndex));
743 +        }
744          modCount++;
745 <        int numMoved = size - toIndex;
746 <        System.arraycopy(elementData, toIndex, elementData, fromIndex,
554 <                         numMoved);
555 <
556 <        // Let gc do its work
557 <        int newSize = size - (toIndex-fromIndex);
558 <        while (size != newSize)
559 <            elementData[--size] = null;
745 >        shiftTailOverGap(elementData, fromIndex, toIndex);
746 >        // checkInvariants();
747      }
748  
749 <    /**
750 <     * Checks if the given index is in range.  If not, throws an appropriate
751 <     * runtime exception.  This method does *not* check if the index is
752 <     * negative: It is always used immediately prior to an array access,
753 <     * which throws an ArrayIndexOutOfBoundsException if index is negative.
567 <     */
568 <    private void rangeCheck(int index) {
569 <        if (index >= size)
570 <            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
749 >    /** Erases the gap from lo to hi, by sliding down following elements. */
750 >    private void shiftTailOverGap(Object[] es, int lo, int hi) {
751 >        System.arraycopy(es, hi, es, lo, size - hi);
752 >        for (int to = size, i = (size -= hi - lo); i < to; i++)
753 >            es[i] = null;
754      }
755  
756      /**
# Line 588 | Line 771 | public class ArrayList<E> extends Abstra
771      }
772  
773      /**
774 +     * A version used in checking (fromIndex > toIndex) condition
775 +     */
776 +    private static String outOfBoundsMsg(int fromIndex, int toIndex) {
777 +        return "From Index: " + fromIndex + " > To Index: " + toIndex;
778 +    }
779 +
780 +    /**
781       * Removes from this list all of its elements that are contained in the
782       * specified collection.
783       *
784       * @param c collection containing elements to be removed from this list
785       * @return {@code true} if this list changed as a result of the call
786       * @throws ClassCastException if the class of an element of this list
787 <     *         is incompatible with the specified collection (optional)
787 >     *         is incompatible with the specified collection
788 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
789       * @throws NullPointerException if this list contains a null element and the
790 <     *         specified collection does not permit null elements (optional),
790 >     *         specified collection does not permit null elements
791 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
792       *         or if the specified collection is null
793       * @see Collection#contains(Object)
794       */
795      public boolean removeAll(Collection<?> c) {
796 <        return batchRemove(c, false);
796 >        return batchRemove(c, false, 0, size);
797      }
798  
799      /**
# Line 612 | Line 804 | public class ArrayList<E> extends Abstra
804       * @param c collection containing elements to be retained in this list
805       * @return {@code true} if this list changed as a result of the call
806       * @throws ClassCastException if the class of an element of this list
807 <     *         is incompatible with the specified collection (optional)
807 >     *         is incompatible with the specified collection
808 >     * (<a href="Collection.html#optional-restrictions">optional</a>)
809       * @throws NullPointerException if this list contains a null element and the
810 <     *         specified collection does not permit null elements (optional),
810 >     *         specified collection does not permit null elements
811 >     * (<a href="Collection.html#optional-restrictions">optional</a>),
812       *         or if the specified collection is null
813       * @see Collection#contains(Object)
814       */
815      public boolean retainAll(Collection<?> c) {
816 <        return batchRemove(c, true);
816 >        return batchRemove(c, true, 0, size);
817      }
818  
819 <    private boolean batchRemove(Collection<?> c, boolean complement) {
820 <        final Object[] elementData = this.elementData;
821 <        int r = 0, w = 0;
822 <        boolean modified = false;
819 >    boolean batchRemove(Collection<?> c, boolean complement,
820 >                        final int from, final int end) {
821 >        Objects.requireNonNull(c);
822 >        final Object[] es = elementData;
823 >        int r;
824 >        // Optimize for initial run of survivors
825 >        for (r = from;; r++) {
826 >            if (r == end)
827 >                return false;
828 >            if (c.contains(es[r]) != complement)
829 >                break;
830 >        }
831 >        int w = r++;
832          try {
833 <            for (; r < size; r++)
834 <                if (c.contains(elementData[r]) == complement)
835 <                    elementData[w++] = elementData[r];
836 <        } finally {
833 >            for (Object e; r < end; r++)
834 >                if (c.contains(e = es[r]) == complement)
835 >                    es[w++] = e;
836 >        } catch (Throwable ex) {
837              // Preserve behavioral compatibility with AbstractCollection,
838              // even if c.contains() throws.
839 <            if (r != size) {
840 <                System.arraycopy(elementData, r,
841 <                                 elementData, w,
842 <                                 size - r);
843 <                w += size - r;
844 <            }
642 <            if (w != size) {
643 <                for (int i = w; i < size; i++)
644 <                    elementData[i] = null;
645 <                modCount += size - w;
646 <                size = w;
647 <                modified = true;
648 <            }
839 >            System.arraycopy(es, r, es, w, end - r);
840 >            w += end - r;
841 >            throw ex;
842 >        } finally {
843 >            modCount += end - w;
844 >            shiftTailOverGap(es, w, end);
845          }
846 <        return modified;
846 >        // checkInvariants();
847 >        return true;
848      }
849  
850      /**
851 <     * Save the state of the <tt>ArrayList</tt> instance to a stream (that
852 <     * is, serialize it).
851 >     * Saves the state of the {@code ArrayList} instance to a stream
852 >     * (that is, serializes it).
853       *
854 <     * @serialData The length of the array backing the <tt>ArrayList</tt>
854 >     * @param s the stream
855 >     * @throws java.io.IOException if an I/O error occurs
856 >     * @serialData The length of the array backing the {@code ArrayList}
857       *             instance is emitted (int), followed by all of its elements
858 <     *             (each an <tt>Object</tt>) in the proper order.
858 >     *             (each an {@code Object}) in the proper order.
859       */
860 +    // OPENJDK @java.io.Serial
861      private void writeObject(java.io.ObjectOutputStream s)
862 <        throws java.io.IOException{
862 >        throws java.io.IOException {
863          // Write out element count, and any hidden stuff
864          int expectedModCount = modCount;
865          s.defaultWriteObject();
866  
867 <        // Write out array length
868 <        s.writeInt(elementData.length);
867 >        // Write out size as capacity for behavioral compatibility with clone()
868 >        s.writeInt(size);
869  
870          // Write out all elements in the proper order.
871 <        for (int i=0; i<size; i++)
871 >        for (int i=0; i<size; i++) {
872              s.writeObject(elementData[i]);
873 +        }
874  
875          if (modCount != expectedModCount) {
876              throw new ConcurrentModificationException();
877          }
677
878      }
879  
880      /**
881 <     * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
882 <     * deserialize it).
881 >     * Reconstitutes the {@code ArrayList} instance from a stream (that is,
882 >     * deserializes it).
883 >     * @param s the stream
884 >     * @throws ClassNotFoundException if the class of a serialized object
885 >     *         could not be found
886 >     * @throws java.io.IOException if an I/O error occurs
887       */
888 +    // OPENJDK @java.io.Serial
889      private void readObject(java.io.ObjectInputStream s)
890          throws java.io.IOException, ClassNotFoundException {
891 +
892          // Read in size, and any hidden stuff
893          s.defaultReadObject();
894  
895 <        // Read in array length and allocate array
896 <        int arrayLength = s.readInt();
897 <        Object[] a = elementData = new Object[arrayLength];
898 <
899 <        // Read in all elements in the proper order.
900 <        for (int i=0; i<size; i++)
901 <            a[i] = s.readObject();
895 >        // Read in capacity
896 >        s.readInt(); // ignored
897 >
898 >        if (size > 0) {
899 >            // like clone(), allocate array based upon size not capacity
900 >            jsr166.Platform.checkArray(s, Object[].class, size);
901 >            Object[] elements = new Object[size];
902 >
903 >            // Read in all elements in the proper order.
904 >            for (int i = 0; i < size; i++) {
905 >                elements[i] = s.readObject();
906 >            }
907 >
908 >            elementData = elements;
909 >        } else if (size == 0) {
910 >            elementData = EMPTY_ELEMENTDATA;
911 >        } else {
912 >            throw new java.io.InvalidObjectException("Invalid size: " + size);
913 >        }
914      }
915  
916      /**
# Line 708 | Line 926 | public class ArrayList<E> extends Abstra
926       * @throws IndexOutOfBoundsException {@inheritDoc}
927       */
928      public ListIterator<E> listIterator(int index) {
929 <        if (index < 0 || index > size)
712 <            throw new IndexOutOfBoundsException("Index: "+index);
929 >        rangeCheckForAdd(index);
930          return new ListItr(index);
931      }
932  
# Line 744 | Line 961 | public class ArrayList<E> extends Abstra
961          int lastRet = -1; // index of last element returned; -1 if no such
962          int expectedModCount = modCount;
963  
964 +        // prevent creating a synthetic constructor
965 +        Itr() {}
966 +
967          public boolean hasNext() {
968              return cursor != size;
969          }
# Line 776 | Line 996 | public class ArrayList<E> extends Abstra
996              }
997          }
998  
999 +        @Override
1000 +        public void forEachRemaining(Consumer<? super E> action) {
1001 +            Objects.requireNonNull(action);
1002 +            final int size = ArrayList.this.size;
1003 +            int i = cursor;
1004 +            if (i < size) {
1005 +                final Object[] es = elementData;
1006 +                if (i >= es.length)
1007 +                    throw new ConcurrentModificationException();
1008 +                for (; i < size && modCount == expectedModCount; i++)
1009 +                    action.accept(elementAt(es, i));
1010 +                // update once at end to reduce heap write traffic
1011 +                cursor = i;
1012 +                lastRet = i - 1;
1013 +                checkForComodification();
1014 +            }
1015 +        }
1016 +
1017          final void checkForComodification() {
1018              if (modCount != expectedModCount)
1019                  throw new ConcurrentModificationException();
# Line 874 | Line 1112 | public class ArrayList<E> extends Abstra
1112       */
1113      public List<E> subList(int fromIndex, int toIndex) {
1114          subListRangeCheck(fromIndex, toIndex, size);
1115 <        return new SubList(this, 0, fromIndex, toIndex);
1115 >        return new SubList<>(this, fromIndex, toIndex);
1116      }
1117  
1118 <    static void subListRangeCheck(int fromIndex, int toIndex, int size) {
1119 <        if (fromIndex < 0)
1120 <            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
883 <        if (toIndex > size)
884 <            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
885 <        if (fromIndex > toIndex)
886 <            throw new IllegalArgumentException("fromIndex(" + fromIndex +
887 <                                               ") > toIndex(" + toIndex + ")");
888 <    }
889 <
890 <    private class SubList extends AbstractList<E> implements RandomAccess {
891 <        private final AbstractList<E> parent;
892 <        private final int parentOffset;
1118 >    private static class SubList<E> extends AbstractList<E> implements RandomAccess {
1119 >        private final ArrayList<E> root;
1120 >        private final SubList<E> parent;
1121          private final int offset;
1122 <        int size;
1122 >        private int size;
1123  
1124 <        SubList(AbstractList<E> parent,
1125 <                int offset, int fromIndex, int toIndex) {
1124 >        /**
1125 >         * Constructs a sublist of an arbitrary ArrayList.
1126 >         */
1127 >        public SubList(ArrayList<E> root, int fromIndex, int toIndex) {
1128 >            this.root = root;
1129 >            this.parent = null;
1130 >            this.offset = fromIndex;
1131 >            this.size = toIndex - fromIndex;
1132 >            this.modCount = root.modCount;
1133 >        }
1134 >
1135 >        /**
1136 >         * Constructs a sublist of another SubList.
1137 >         */
1138 >        private SubList(SubList<E> parent, int fromIndex, int toIndex) {
1139 >            this.root = parent.root;
1140              this.parent = parent;
1141 <            this.parentOffset = fromIndex;
900 <            this.offset = offset + fromIndex;
1141 >            this.offset = parent.offset + fromIndex;
1142              this.size = toIndex - fromIndex;
1143 <            this.modCount = ArrayList.this.modCount;
1143 >            this.modCount = parent.modCount;
1144          }
1145  
1146 <        public E set(int index, E e) {
1147 <            rangeCheck(index);
1146 >        public E set(int index, E element) {
1147 >            Objects.checkIndex(index, size);
1148              checkForComodification();
1149 <            E oldValue = ArrayList.this.elementData(offset + index);
1150 <            ArrayList.this.elementData[offset + index] = e;
1149 >            E oldValue = root.elementData(offset + index);
1150 >            root.elementData[offset + index] = element;
1151              return oldValue;
1152          }
1153  
1154          public E get(int index) {
1155 <            rangeCheck(index);
1155 >            Objects.checkIndex(index, size);
1156              checkForComodification();
1157 <            return ArrayList.this.elementData(offset + index);
1157 >            return root.elementData(offset + index);
1158          }
1159  
1160          public int size() {
1161              checkForComodification();
1162 <            return this.size;
1162 >            return size;
1163          }
1164  
1165 <        public void add(int index, E e) {
1165 >        public void add(int index, E element) {
1166              rangeCheckForAdd(index);
1167              checkForComodification();
1168 <            parent.add(parentOffset + index, e);
1169 <            this.modCount = parent.modCount;
929 <            this.size++;
1168 >            root.add(offset + index, element);
1169 >            updateSizeAndModCount(1);
1170          }
1171  
1172          public E remove(int index) {
1173 <            rangeCheck(index);
1173 >            Objects.checkIndex(index, size);
1174              checkForComodification();
1175 <            E result = parent.remove(parentOffset + index);
1176 <            this.modCount = parent.modCount;
937 <            this.size--;
1175 >            E result = root.remove(offset + index);
1176 >            updateSizeAndModCount(-1);
1177              return result;
1178          }
1179  
1180          protected void removeRange(int fromIndex, int toIndex) {
1181              checkForComodification();
1182 <            parent.removeRange(parentOffset + fromIndex,
1183 <                               parentOffset + toIndex);
945 <            this.modCount = parent.modCount;
946 <            this.size -= toIndex - fromIndex;
1182 >            root.removeRange(offset + fromIndex, offset + toIndex);
1183 >            updateSizeAndModCount(fromIndex - toIndex);
1184          }
1185  
1186          public boolean addAll(Collection<? extends E> c) {
# Line 955 | Line 1192 | public class ArrayList<E> extends Abstra
1192              int cSize = c.size();
1193              if (cSize==0)
1194                  return false;
958
1195              checkForComodification();
1196 <            parent.addAll(parentOffset + index, c);
1197 <            this.modCount = parent.modCount;
962 <            this.size += cSize;
1196 >            root.addAll(offset + index, c);
1197 >            updateSizeAndModCount(cSize);
1198              return true;
1199          }
1200  
1201 +        public void replaceAll(UnaryOperator<E> operator) {
1202 +            root.replaceAllRange(operator, offset, offset + size);
1203 +        }
1204 +
1205 +        public boolean removeAll(Collection<?> c) {
1206 +            return batchRemove(c, false);
1207 +        }
1208 +
1209 +        public boolean retainAll(Collection<?> c) {
1210 +            return batchRemove(c, true);
1211 +        }
1212 +
1213 +        private boolean batchRemove(Collection<?> c, boolean complement) {
1214 +            checkForComodification();
1215 +            int oldSize = root.size;
1216 +            boolean modified =
1217 +                root.batchRemove(c, complement, offset, offset + size);
1218 +            if (modified)
1219 +                updateSizeAndModCount(root.size - oldSize);
1220 +            return modified;
1221 +        }
1222 +
1223 +        public boolean removeIf(Predicate<? super E> filter) {
1224 +            checkForComodification();
1225 +            int oldSize = root.size;
1226 +            boolean modified = root.removeIf(filter, offset, offset + size);
1227 +            if (modified)
1228 +                updateSizeAndModCount(root.size - oldSize);
1229 +            return modified;
1230 +        }
1231 +
1232 +        public Object[] toArray() {
1233 +            checkForComodification();
1234 +            return Arrays.copyOfRange(root.elementData, offset, offset + size);
1235 +        }
1236 +
1237 +        @SuppressWarnings("unchecked")
1238 +        public <T> T[] toArray(T[] a) {
1239 +            checkForComodification();
1240 +            if (a.length < size)
1241 +                return (T[]) Arrays.copyOfRange(
1242 +                        root.elementData, offset, offset + size, a.getClass());
1243 +            System.arraycopy(root.elementData, offset, a, 0, size);
1244 +            if (a.length > size)
1245 +                a[size] = null;
1246 +            return a;
1247 +        }
1248 +
1249 +        public boolean equals(Object o) {
1250 +            if (o == this) {
1251 +                return true;
1252 +            }
1253 +
1254 +            if (!(o instanceof List)) {
1255 +                return false;
1256 +            }
1257 +
1258 +            boolean equal = root.equalsRange((List<?>)o, offset, offset + size);
1259 +            checkForComodification();
1260 +            return equal;
1261 +        }
1262 +
1263 +        public int hashCode() {
1264 +            int hash = root.hashCodeRange(offset, offset + size);
1265 +            checkForComodification();
1266 +            return hash;
1267 +        }
1268 +
1269 +        public int indexOf(Object o) {
1270 +            int index = root.indexOfRange(o, offset, offset + size);
1271 +            checkForComodification();
1272 +            return index >= 0 ? index - offset : -1;
1273 +        }
1274 +
1275 +        public int lastIndexOf(Object o) {
1276 +            int index = root.lastIndexOfRange(o, offset, offset + size);
1277 +            checkForComodification();
1278 +            return index >= 0 ? index - offset : -1;
1279 +        }
1280 +
1281 +        public boolean contains(Object o) {
1282 +            return indexOf(o) >= 0;
1283 +        }
1284 +
1285          public Iterator<E> iterator() {
1286              return listIterator();
1287          }
1288  
1289 <        public ListIterator<E> listIterator(final int index) {
1289 >        public ListIterator<E> listIterator(int index) {
1290              checkForComodification();
1291              rangeCheckForAdd(index);
973            final int offset = this.offset;
1292  
1293              return new ListIterator<E>() {
1294                  int cursor = index;
1295                  int lastRet = -1;
1296 <                int expectedModCount = ArrayList.this.modCount;
1296 >                int expectedModCount = SubList.this.modCount;
1297  
1298                  public boolean hasNext() {
1299                      return cursor != SubList.this.size;
# Line 987 | Line 1305 | public class ArrayList<E> extends Abstra
1305                      int i = cursor;
1306                      if (i >= SubList.this.size)
1307                          throw new NoSuchElementException();
1308 <                    Object[] elementData = ArrayList.this.elementData;
1308 >                    Object[] elementData = root.elementData;
1309                      if (offset + i >= elementData.length)
1310                          throw new ConcurrentModificationException();
1311                      cursor = i + 1;
# Line 1004 | Line 1322 | public class ArrayList<E> extends Abstra
1322                      int i = cursor - 1;
1323                      if (i < 0)
1324                          throw new NoSuchElementException();
1325 <                    Object[] elementData = ArrayList.this.elementData;
1325 >                    Object[] elementData = root.elementData;
1326                      if (offset + i >= elementData.length)
1327                          throw new ConcurrentModificationException();
1328                      cursor = i;
1329                      return (E) elementData[offset + (lastRet = i)];
1330                  }
1331  
1332 +                public void forEachRemaining(Consumer<? super E> action) {
1333 +                    Objects.requireNonNull(action);
1334 +                    final int size = SubList.this.size;
1335 +                    int i = cursor;
1336 +                    if (i < size) {
1337 +                        final Object[] es = root.elementData;
1338 +                        if (offset + i >= es.length)
1339 +                            throw new ConcurrentModificationException();
1340 +                        for (; i < size && root.modCount == expectedModCount; i++)
1341 +                            action.accept(elementAt(es, offset + i));
1342 +                        // update once at end to reduce heap write traffic
1343 +                        cursor = i;
1344 +                        lastRet = i - 1;
1345 +                        checkForComodification();
1346 +                    }
1347 +                }
1348 +
1349                  public int nextIndex() {
1350                      return cursor;
1351                  }
# Line 1028 | Line 1363 | public class ArrayList<E> extends Abstra
1363                          SubList.this.remove(lastRet);
1364                          cursor = lastRet;
1365                          lastRet = -1;
1366 <                        expectedModCount = ArrayList.this.modCount;
1366 >                        expectedModCount = SubList.this.modCount;
1367                      } catch (IndexOutOfBoundsException ex) {
1368                          throw new ConcurrentModificationException();
1369                      }
# Line 1040 | Line 1375 | public class ArrayList<E> extends Abstra
1375                      checkForComodification();
1376  
1377                      try {
1378 <                        ArrayList.this.set(offset + lastRet, e);
1378 >                        root.set(offset + lastRet, e);
1379                      } catch (IndexOutOfBoundsException ex) {
1380                          throw new ConcurrentModificationException();
1381                      }
# Line 1054 | Line 1389 | public class ArrayList<E> extends Abstra
1389                          SubList.this.add(i, e);
1390                          cursor = i + 1;
1391                          lastRet = -1;
1392 <                        expectedModCount = ArrayList.this.modCount;
1392 >                        expectedModCount = SubList.this.modCount;
1393                      } catch (IndexOutOfBoundsException ex) {
1394                          throw new ConcurrentModificationException();
1395                      }
1396                  }
1397  
1398                  final void checkForComodification() {
1399 <                    if (expectedModCount != ArrayList.this.modCount)
1399 >                    if (root.modCount != expectedModCount)
1400                          throw new ConcurrentModificationException();
1401                  }
1402              };
# Line 1069 | Line 1404 | public class ArrayList<E> extends Abstra
1404  
1405          public List<E> subList(int fromIndex, int toIndex) {
1406              subListRangeCheck(fromIndex, toIndex, size);
1407 <            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));
1407 >            return new SubList<>(this, fromIndex, toIndex);
1408          }
1409  
1410          private void rangeCheckForAdd(int index) {
# Line 1087 | Line 1417 | public class ArrayList<E> extends Abstra
1417          }
1418  
1419          private void checkForComodification() {
1420 <            if (ArrayList.this.modCount != this.modCount)
1420 >            if (root.modCount != modCount)
1421                  throw new ConcurrentModificationException();
1422          }
1423 +
1424 +        private void updateSizeAndModCount(int sizeChange) {
1425 +            SubList<E> slist = this;
1426 +            do {
1427 +                slist.size += sizeChange;
1428 +                slist.modCount = root.modCount;
1429 +                slist = slist.parent;
1430 +            } while (slist != null);
1431 +        }
1432 +
1433 +        public Spliterator<E> spliterator() {
1434 +            checkForComodification();
1435 +
1436 +            // ArrayListSpliterator not used here due to late-binding
1437 +            return new Spliterator<E>() {
1438 +                private int index = offset; // current index, modified on advance/split
1439 +                private int fence = -1; // -1 until used; then one past last index
1440 +                private int expectedModCount; // initialized when fence set
1441 +
1442 +                private int getFence() { // initialize fence to size on first use
1443 +                    int hi; // (a specialized variant appears in method forEach)
1444 +                    if ((hi = fence) < 0) {
1445 +                        expectedModCount = modCount;
1446 +                        hi = fence = offset + size;
1447 +                    }
1448 +                    return hi;
1449 +                }
1450 +
1451 +                public ArrayList<E>.ArrayListSpliterator trySplit() {
1452 +                    int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1453 +                    // ArrayListSpliterator can be used here as the source is already bound
1454 +                    return (lo >= mid) ? null : // divide range in half unless too small
1455 +                        root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
1456 +                }
1457 +
1458 +                public boolean tryAdvance(Consumer<? super E> action) {
1459 +                    Objects.requireNonNull(action);
1460 +                    int hi = getFence(), i = index;
1461 +                    if (i < hi) {
1462 +                        index = i + 1;
1463 +                        @SuppressWarnings("unchecked") E e = (E)root.elementData[i];
1464 +                        action.accept(e);
1465 +                        if (root.modCount != expectedModCount)
1466 +                            throw new ConcurrentModificationException();
1467 +                        return true;
1468 +                    }
1469 +                    return false;
1470 +                }
1471 +
1472 +                public void forEachRemaining(Consumer<? super E> action) {
1473 +                    Objects.requireNonNull(action);
1474 +                    int i, hi, mc; // hoist accesses and checks from loop
1475 +                    ArrayList<E> lst = root;
1476 +                    Object[] a;
1477 +                    if ((a = lst.elementData) != null) {
1478 +                        if ((hi = fence) < 0) {
1479 +                            mc = modCount;
1480 +                            hi = offset + size;
1481 +                        }
1482 +                        else
1483 +                            mc = expectedModCount;
1484 +                        if ((i = index) >= 0 && (index = hi) <= a.length) {
1485 +                            for (; i < hi; ++i) {
1486 +                                @SuppressWarnings("unchecked") E e = (E) a[i];
1487 +                                action.accept(e);
1488 +                            }
1489 +                            if (lst.modCount == mc)
1490 +                                return;
1491 +                        }
1492 +                    }
1493 +                    throw new ConcurrentModificationException();
1494 +                }
1495 +
1496 +                public long estimateSize() {
1497 +                    return getFence() - index;
1498 +                }
1499 +
1500 +                public int characteristics() {
1501 +                    return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1502 +                }
1503 +            };
1504 +        }
1505 +    }
1506 +
1507 +    /**
1508 +     * @throws NullPointerException {@inheritDoc}
1509 +     */
1510 +    @Override
1511 +    public void forEach(Consumer<? super E> action) {
1512 +        Objects.requireNonNull(action);
1513 +        final int expectedModCount = modCount;
1514 +        final Object[] es = elementData;
1515 +        final int size = this.size;
1516 +        for (int i = 0; modCount == expectedModCount && i < size; i++)
1517 +            action.accept(elementAt(es, i));
1518 +        if (modCount != expectedModCount)
1519 +            throw new ConcurrentModificationException();
1520 +    }
1521 +
1522 +    /**
1523 +     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1524 +     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1525 +     * list.
1526 +     *
1527 +     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
1528 +     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.
1529 +     * Overriding implementations should document the reporting of additional
1530 +     * characteristic values.
1531 +     *
1532 +     * @return a {@code Spliterator} over the elements in this list
1533 +     * @since 1.8
1534 +     */
1535 +    @Override
1536 +    public Spliterator<E> spliterator() {
1537 +        return new ArrayListSpliterator(0, -1, 0);
1538 +    }
1539 +
1540 +    /** Index-based split-by-two, lazily initialized Spliterator */
1541 +    final class ArrayListSpliterator implements Spliterator<E> {
1542 +
1543 +        /*
1544 +         * If ArrayLists were immutable, or structurally immutable (no
1545 +         * adds, removes, etc), we could implement their spliterators
1546 +         * with Arrays.spliterator. Instead we detect as much
1547 +         * interference during traversal as practical without
1548 +         * sacrificing much performance. We rely primarily on
1549 +         * modCounts. These are not guaranteed to detect concurrency
1550 +         * violations, and are sometimes overly conservative about
1551 +         * within-thread interference, but detect enough problems to
1552 +         * be worthwhile in practice. To carry this out, we (1) lazily
1553 +         * initialize fence and expectedModCount until the latest
1554 +         * point that we need to commit to the state we are checking
1555 +         * against; thus improving precision.  (This doesn't apply to
1556 +         * SubLists, that create spliterators with current non-lazy
1557 +         * values).  (2) We perform only a single
1558 +         * ConcurrentModificationException check at the end of forEach
1559 +         * (the most performance-sensitive method). When using forEach
1560 +         * (as opposed to iterators), we can normally only detect
1561 +         * interference after actions, not before. Further
1562 +         * CME-triggering checks apply to all other possible
1563 +         * violations of assumptions for example null or too-small
1564 +         * elementData array given its size(), that could only have
1565 +         * occurred due to interference.  This allows the inner loop
1566 +         * of forEach to run without any further checks, and
1567 +         * simplifies lambda-resolution. While this does entail a
1568 +         * number of checks, note that in the common case of
1569 +         * list.stream().forEach(a), no checks or other computation
1570 +         * occur anywhere other than inside forEach itself.  The other
1571 +         * less-often-used methods cannot take advantage of most of
1572 +         * these streamlinings.
1573 +         */
1574 +
1575 +        private int index; // current index, modified on advance/split
1576 +        private int fence; // -1 until used; then one past last index
1577 +        private int expectedModCount; // initialized when fence set
1578 +
1579 +        /** Creates new spliterator covering the given range. */
1580 +        ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1581 +            this.index = origin;
1582 +            this.fence = fence;
1583 +            this.expectedModCount = expectedModCount;
1584 +        }
1585 +
1586 +        private int getFence() { // initialize fence to size on first use
1587 +            int hi; // (a specialized variant appears in method forEach)
1588 +            if ((hi = fence) < 0) {
1589 +                expectedModCount = modCount;
1590 +                hi = fence = size;
1591 +            }
1592 +            return hi;
1593 +        }
1594 +
1595 +        public ArrayListSpliterator trySplit() {
1596 +            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1597 +            return (lo >= mid) ? null : // divide range in half unless too small
1598 +                new ArrayListSpliterator(lo, index = mid, expectedModCount);
1599 +        }
1600 +
1601 +        public boolean tryAdvance(Consumer<? super E> action) {
1602 +            if (action == null)
1603 +                throw new NullPointerException();
1604 +            int hi = getFence(), i = index;
1605 +            if (i < hi) {
1606 +                index = i + 1;
1607 +                @SuppressWarnings("unchecked") E e = (E)elementData[i];
1608 +                action.accept(e);
1609 +                if (modCount != expectedModCount)
1610 +                    throw new ConcurrentModificationException();
1611 +                return true;
1612 +            }
1613 +            return false;
1614 +        }
1615 +
1616 +        public void forEachRemaining(Consumer<? super E> action) {
1617 +            int i, hi, mc; // hoist accesses and checks from loop
1618 +            Object[] a;
1619 +            if (action == null)
1620 +                throw new NullPointerException();
1621 +            if ((a = elementData) != null) {
1622 +                if ((hi = fence) < 0) {
1623 +                    mc = modCount;
1624 +                    hi = size;
1625 +                }
1626 +                else
1627 +                    mc = expectedModCount;
1628 +                if ((i = index) >= 0 && (index = hi) <= a.length) {
1629 +                    for (; i < hi; ++i) {
1630 +                        @SuppressWarnings("unchecked") E e = (E) a[i];
1631 +                        action.accept(e);
1632 +                    }
1633 +                    if (modCount == mc)
1634 +                        return;
1635 +                }
1636 +            }
1637 +            throw new ConcurrentModificationException();
1638 +        }
1639 +
1640 +        public long estimateSize() {
1641 +            return getFence() - index;
1642 +        }
1643 +
1644 +        public int characteristics() {
1645 +            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1646 +        }
1647 +    }
1648 +
1649 +    // A tiny bit set implementation
1650 +
1651 +    private static long[] nBits(int n) {
1652 +        return new long[((n - 1) >> 6) + 1];
1653 +    }
1654 +    private static void setBit(long[] bits, int i) {
1655 +        bits[i >> 6] |= 1L << i;
1656 +    }
1657 +    private static boolean isClear(long[] bits, int i) {
1658 +        return (bits[i >> 6] & (1L << i)) == 0;
1659 +    }
1660 +
1661 +    /**
1662 +     * @throws NullPointerException {@inheritDoc}
1663 +     */
1664 +    @Override
1665 +    public boolean removeIf(Predicate<? super E> filter) {
1666 +        return removeIf(filter, 0, size);
1667 +    }
1668 +
1669 +    /**
1670 +     * Removes all elements satisfying the given predicate, from index
1671 +     * i (inclusive) to index end (exclusive).
1672 +     */
1673 +    boolean removeIf(Predicate<? super E> filter, int i, final int end) {
1674 +        Objects.requireNonNull(filter);
1675 +        int expectedModCount = modCount;
1676 +        final Object[] es = elementData;
1677 +        // Optimize for initial run of survivors
1678 +        for (; i < end && !filter.test(elementAt(es, i)); i++)
1679 +            ;
1680 +        // Tolerate predicates that reentrantly access the collection for
1681 +        // read (but writers still get CME), so traverse once to find
1682 +        // elements to delete, a second pass to physically expunge.
1683 +        if (i < end) {
1684 +            final int beg = i;
1685 +            final long[] deathRow = nBits(end - beg);
1686 +            deathRow[0] = 1L;   // set bit 0
1687 +            for (i = beg + 1; i < end; i++)
1688 +                if (filter.test(elementAt(es, i)))
1689 +                    setBit(deathRow, i - beg);
1690 +            if (modCount != expectedModCount)
1691 +                throw new ConcurrentModificationException();
1692 +            modCount++;
1693 +            int w = beg;
1694 +            for (i = beg; i < end; i++)
1695 +                if (isClear(deathRow, i - beg))
1696 +                    es[w++] = es[i];
1697 +            shiftTailOverGap(es, w, end);
1698 +            // checkInvariants();
1699 +            return true;
1700 +        } else {
1701 +            if (modCount != expectedModCount)
1702 +                throw new ConcurrentModificationException();
1703 +            // checkInvariants();
1704 +            return false;
1705 +        }
1706 +    }
1707 +
1708 +    @Override
1709 +    public void replaceAll(UnaryOperator<E> operator) {
1710 +        replaceAllRange(operator, 0, size);
1711 +        // TODO(8203662): remove increment of modCount from ...
1712 +        modCount++;
1713 +    }
1714 +
1715 +    private void replaceAllRange(UnaryOperator<E> operator, int i, int end) {
1716 +        Objects.requireNonNull(operator);
1717 +        final int expectedModCount = modCount;
1718 +        final Object[] es = elementData;
1719 +        for (; modCount == expectedModCount && i < end; i++)
1720 +            es[i] = operator.apply(elementAt(es, i));
1721 +        if (modCount != expectedModCount)
1722 +            throw new ConcurrentModificationException();
1723 +        // checkInvariants();
1724 +    }
1725 +
1726 +    @Override
1727 +    @SuppressWarnings("unchecked")
1728 +    public void sort(Comparator<? super E> c) {
1729 +        final int expectedModCount = modCount;
1730 +        Arrays.sort((E[]) elementData, 0, size, c);
1731 +        if (modCount != expectedModCount)
1732 +            throw new ConcurrentModificationException();
1733 +        modCount++;
1734 +        // checkInvariants();
1735 +    }
1736 +
1737 +    void checkInvariants() {
1738 +        // assert size >= 0;
1739 +        // assert size == elementData.length || elementData[size] == null;
1740      }
1741   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines