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.29 by jsr166, Tue Jul 21 23:56:46 2009 UTC vs.
Revision 1.68 by jsr166, Sat Aug 10 16:48:05 2019 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines