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