ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayList.java
Revision: 1.69
Committed: Fri Aug 30 18:05:39 2019 UTC (4 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.68: +3 -0 lines
Log Message:
accommodate 8229997: Apply java.io.Serial annotations in java.base

File Contents

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