ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayList.java
Revision: 1.71
Committed: Fri Jul 24 20:57:26 2020 UTC (3 years, 9 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.70: +8 -7 lines
Log Message:
8231800: Better listing of arrays

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