ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayList.java
Revision: 1.70
Committed: Fri Jan 10 21:32:08 2020 UTC (4 years, 3 months ago) by jsr166
Branch: MAIN
Changes since 1.69: +5 -5 lines
Log Message:
8234423: Modifying ArrayList.subList().subList() resets modCount of subList

File Contents

# User Rev Content
1 dl 1.1 /*
2 jsr166 1.67 * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
3 jsr166 1.24 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 dl 1.1 *
5 jsr166 1.24 * 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 jsr166 1.33 * published by the Free Software Foundation. Oracle designates this
8 jsr166 1.24 * particular file as subject to the "Classpath" exception as provided
9 jsr166 1.33 * by Oracle in the LICENSE file that accompanied this code.
10 jsr166 1.24 *
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 jsr166 1.30 * 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 dl 1.1 */
25    
26     package java.util;
27    
28 jsr166 1.33 import java.util.function.Consumer;
29     import java.util.function.Predicate;
30     import java.util.function.UnaryOperator;
31 jsr166 1.65 // OPENJDK import jdk.internal.access.SharedSecrets;
32 jsr166 1.67 import jdk.internal.util.ArraysSupport;
33 jsr166 1.33
34 dl 1.1 /**
35 jsr166 1.33 * Resizable-array implementation of the {@code List} interface. Implements
36 dl 1.1 * all optional list operations, and permits all elements, including
37 jsr166 1.33 * {@code null}. In addition to implementing the {@code List} interface,
38 dl 1.1 * 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 jsr166 1.33 * {@code Vector}, except that it is unsynchronized.)
41 dl 1.1 *
42 jsr166 1.33 * <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 dl 1.1 * 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 jsr166 1.33 * to that for the {@code LinkedList} implementation.
48 dl 1.1 *
49 jsr166 1.33 * <p>Each {@code ArrayList} instance has a <i>capacity</i>. The capacity is
50 dl 1.1 * 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 jsr166 1.25 * time cost.
55 dl 1.1 *
56 jsr166 1.33 * <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 dl 1.1 * operation. This may reduce the amount of incremental reallocation.
59     *
60     * <p><strong>Note that this implementation is not synchronized.</strong>
61 jsr166 1.33 * If multiple threads access an {@code ArrayList} instance concurrently,
62 dl 1.1 * 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 jsr166 1.33 * <p id="fail-fast">
76 jsr166 1.25 * 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 dl 1.1 *
87 jsr166 1.25 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
88 dl 1.1 * as it is, generally speaking, impossible to make any hard guarantees in the
89     * presence of unsynchronized concurrent modification. Fail-fast iterators
90 jsr166 1.25 * throw {@code ConcurrentModificationException} on a best-effort basis.
91 dl 1.1 * Therefore, it would be wrong to write a program that depended on this
92 jsr166 1.25 * exception for its correctness: <i>the fail-fast behavior of iterators
93     * should be used only to detect bugs.</i>
94 dl 1.1 *
95 jsr166 1.25 * <p>This class is a member of the
96 jsr166 1.64 * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
97 dl 1.1 * Java Collections Framework</a>.
98     *
99 jsr166 1.33 * @param <E> the type of elements in this list
100     *
101 dl 1.1 * @author Josh Bloch
102     * @author Neal Gafter
103 jsr166 1.26 * @see Collection
104     * @see List
105     * @see LinkedList
106     * @see Vector
107 dl 1.1 * @since 1.2
108     */
109     public class ArrayList<E> extends AbstractList<E>
110     implements List<E>, RandomAccess, Cloneable, java.io.Serializable
111     {
112 jsr166 1.69 // OPENJDK @java.io.Serial
113 dl 1.1 private static final long serialVersionUID = 8683452581122892189L;
114    
115     /**
116 jsr166 1.33 * 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 dl 1.1 * The array buffer into which the elements of the ArrayList are stored.
134 jsr166 1.33 * 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 dl 1.1 */
138 jsr166 1.33 transient Object[] elementData; // non-private to simplify nested class access
139 dl 1.1
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 jsr166 1.31 * @param initialCapacity the initial capacity of the list
151     * @throws IllegalArgumentException if the specified initial capacity
152     * is negative
153 dl 1.1 */
154     public ArrayList(int initialCapacity) {
155 jsr166 1.33 if (initialCapacity > 0) {
156     this.elementData = new Object[initialCapacity];
157     } else if (initialCapacity == 0) {
158     this.elementData = EMPTY_ELEMENTDATA;
159     } else {
160 dl 1.1 throw new IllegalArgumentException("Illegal Capacity: "+
161     initialCapacity);
162 jsr166 1.33 }
163 dl 1.1 }
164    
165     /**
166     * Constructs an empty list with an initial capacity of ten.
167     */
168     public ArrayList() {
169 jsr166 1.33 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
170 dl 1.1 }
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 jsr166 1.17 * iterator.
176 dl 1.1 *
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 jsr166 1.26 elementData = c.toArray();
182 jsr166 1.33 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 dl 1.2 }
192 jsr166 1.4
193 dl 1.1 /**
194 jsr166 1.33 * Trims the capacity of this {@code ArrayList} instance to be the
195 dl 1.1 * list's current size. An application can use this operation to minimize
196 jsr166 1.33 * the storage of an {@code ArrayList} instance.
197 dl 1.1 */
198     public void trimToSize() {
199 jsr166 1.26 modCount++;
200 jsr166 1.33 if (size < elementData.length) {
201     elementData = (size == 0)
202     ? EMPTY_ELEMENTDATA
203     : Arrays.copyOf(elementData, size);
204 jsr166 1.26 }
205 dl 1.1 }
206    
207     /**
208 jsr166 1.33 * Increases the capacity of this {@code ArrayList} instance, if
209 dl 1.1 * necessary, to ensure that it can hold at least the number of elements
210     * specified by the minimum capacity argument.
211     *
212 jsr166 1.33 * @param minCapacity the desired minimum capacity
213 dl 1.1 */
214     public void ensureCapacity(int minCapacity) {
215 jsr166 1.33 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 jsr166 1.67 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 jsr166 1.33 }
241    
242     private Object[] grow() {
243     return grow(size + 1);
244     }
245    
246     /**
247 dl 1.1 * Returns the number of elements in this list.
248     *
249     * @return the number of elements in this list
250     */
251     public int size() {
252 jsr166 1.26 return size;
253 dl 1.1 }
254    
255     /**
256 jsr166 1.33 * Returns {@code true} if this list contains no elements.
257 dl 1.1 *
258 jsr166 1.33 * @return {@code true} if this list contains no elements
259 dl 1.1 */
260     public boolean isEmpty() {
261 jsr166 1.26 return size == 0;
262 dl 1.1 }
263    
264     /**
265 jsr166 1.33 * 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 dl 1.1 *
270     * @param o element whose presence in this list is to be tested
271 jsr166 1.33 * @return {@code true} if this list contains the specified element
272 dl 1.1 */
273     public boolean contains(Object o) {
274 jsr166 1.26 return indexOf(o) >= 0;
275 dl 1.1 }
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 jsr166 1.33 * More formally, returns the lowest index {@code i} such that
281     * {@code Objects.equals(o, get(i))},
282 dl 1.1 * or -1 if there is no such index.
283     */
284     public int indexOf(Object o) {
285 jsr166 1.60 return indexOfRange(o, 0, size);
286     }
287    
288     int indexOfRange(Object o, int start, int end) {
289     Object[] es = elementData;
290 jsr166 1.26 if (o == null) {
291 jsr166 1.60 for (int i = start; i < end; i++) {
292     if (es[i] == null) {
293 jsr166 1.26 return i;
294 jsr166 1.60 }
295     }
296 jsr166 1.26 } else {
297 jsr166 1.60 for (int i = start; i < end; i++) {
298     if (o.equals(es[i])) {
299 jsr166 1.26 return i;
300 jsr166 1.60 }
301     }
302 jsr166 1.26 }
303     return -1;
304 dl 1.1 }
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 jsr166 1.33 * More formally, returns the highest index {@code i} such that
310     * {@code Objects.equals(o, get(i))},
311 dl 1.1 * or -1 if there is no such index.
312     */
313     public int lastIndexOf(Object o) {
314 jsr166 1.60 return lastIndexOfRange(o, 0, size);
315     }
316    
317     int lastIndexOfRange(Object o, int start, int end) {
318     Object[] es = elementData;
319 jsr166 1.26 if (o == null) {
320 jsr166 1.60 for (int i = end - 1; i >= start; i--) {
321     if (es[i] == null) {
322 jsr166 1.26 return i;
323 jsr166 1.60 }
324     }
325 jsr166 1.26 } else {
326 jsr166 1.60 for (int i = end - 1; i >= start; i--) {
327     if (o.equals(es[i])) {
328 jsr166 1.26 return i;
329 jsr166 1.60 }
330     }
331 jsr166 1.26 }
332     return -1;
333 dl 1.1 }
334    
335     /**
336 jsr166 1.33 * Returns a shallow copy of this {@code ArrayList} instance. (The
337 dl 1.1 * elements themselves are not copied.)
338     *
339 jsr166 1.33 * @return a clone of this {@code ArrayList} instance
340 dl 1.1 */
341     public Object clone() {
342 jsr166 1.26 try {
343 jsr166 1.33 ArrayList<?> v = (ArrayList<?>) super.clone();
344 jsr166 1.26 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 jsr166 1.33 throw new InternalError(e);
350 jsr166 1.26 }
351 dl 1.1 }
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 jsr166 1.33 * {@code null}. (This is useful in determining the length of the
383 dl 1.1 * 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 jsr166 1.25 @SuppressWarnings("unchecked")
396 dl 1.1 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 jsr166 1.26 System.arraycopy(elementData, 0, a, 0, size);
401 dl 1.1 if (a.length > size)
402     a[size] = null;
403     return a;
404     }
405    
406     // Positional Access Operations
407    
408 jsr166 1.25 @SuppressWarnings("unchecked")
409     E elementData(int index) {
410 jsr166 1.26 return (E) elementData[index];
411 dl 1.1 }
412    
413 jsr166 1.39 @SuppressWarnings("unchecked")
414     static <E> E elementAt(Object[] es, int index) {
415     return (E) es[index];
416     }
417    
418 dl 1.1 /**
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 jsr166 1.33 Objects.checkIndex(index, size);
427 jsr166 1.26 return elementData(index);
428 dl 1.1 }
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 jsr166 1.33 Objects.checkIndex(index, size);
441 jsr166 1.26 E oldValue = elementData(index);
442     elementData[index] = element;
443     return oldValue;
444 dl 1.1 }
445    
446     /**
447 jsr166 1.33 * 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 dl 1.1 * Appends the specified element to the end of this list.
460     *
461     * @param e element to be appended to this list
462 jsr166 1.33 * @return {@code true} (as specified by {@link Collection#add})
463 dl 1.1 */
464     public boolean add(E e) {
465 jsr166 1.33 modCount++;
466     add(e, elementData, size);
467 jsr166 1.26 return true;
468 dl 1.1 }
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 jsr166 1.26 rangeCheckForAdd(index);
481 jsr166 1.33 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 jsr166 1.26 elementData[index] = element;
490 jsr166 1.33 size = s + 1;
491 jsr166 1.41 // checkInvariants();
492 dl 1.1 }
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 jsr166 1.33 Objects.checkIndex(index, size);
505 jsr166 1.51 final Object[] es = elementData;
506 jsr166 1.25
507 jsr166 1.51 @SuppressWarnings("unchecked") E oldValue = (E) es[index];
508     fastRemove(es, index);
509 jsr166 1.25
510 jsr166 1.41 // checkInvariants();
511 jsr166 1.26 return oldValue;
512 dl 1.1 }
513    
514     /**
515 jsr166 1.60 * {@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 jsr166 1.68 var oit = other.iterator();
543 jsr166 1.60 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 dl 1.1 * 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 jsr166 1.33 * {@code i} such that
606     * {@code Objects.equals(o, get(i))}
607     * (if such an element exists). Returns {@code true} if this list
608 dl 1.1 * 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 jsr166 1.33 * @return {@code true} if this list contained the specified element
613 dl 1.1 */
614     public boolean remove(Object o) {
615 jsr166 1.51 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 dl 1.1 }
630 jsr166 1.51 fastRemove(es, i);
631     return true;
632 dl 1.1 }
633    
634 jsr166 1.41 /**
635 dl 1.1 * Private remove method that skips bounds checking and does not
636     * return the value removed.
637     */
638 jsr166 1.51 private void fastRemove(Object[] es, int i) {
639 dl 1.1 modCount++;
640 jsr166 1.51 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 dl 1.1 }
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 jsr166 1.26 modCount++;
652 jsr166 1.47 final Object[] es = elementData;
653     for (int to = size, i = size = 0; i < to; i++)
654     es[i] = null;
655 dl 1.1 }
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 jsr166 1.33 * @return {@code true} if this list changed as a result of the call
668 dl 1.1 * @throws NullPointerException if the specified collection is null
669     */
670     public boolean addAll(Collection<? extends E> c) {
671 jsr166 1.26 Object[] a = c.toArray();
672 jsr166 1.33 modCount++;
673 dl 1.1 int numNew = a.length;
674 jsr166 1.33 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 jsr166 1.41 // checkInvariants();
683 jsr166 1.33 return true;
684 dl 1.1 }
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 jsr166 1.33 * @return {@code true} if this list changed as a result of the call
698 dl 1.1 * @throws IndexOutOfBoundsException {@inheritDoc}
699     * @throws NullPointerException if the specified collection is null
700     */
701     public boolean addAll(int index, Collection<? extends E> c) {
702 jsr166 1.26 rangeCheckForAdd(index);
703 dl 1.1
704 jsr166 1.26 Object[] a = c.toArray();
705 jsr166 1.33 modCount++;
706 jsr166 1.26 int numNew = a.length;
707 jsr166 1.33 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 jsr166 1.26
714 jsr166 1.33 int numMoved = s - index;
715 jsr166 1.26 if (numMoved > 0)
716 jsr166 1.33 System.arraycopy(elementData, index,
717     elementData, index + numNew,
718 jsr166 1.26 numMoved);
719 dl 1.1 System.arraycopy(a, 0, elementData, index, numNew);
720 jsr166 1.33 size = s + numNew;
721 jsr166 1.41 // checkInvariants();
722 jsr166 1.33 return true;
723 dl 1.1 }
724    
725     /**
726     * Removes from this list all of the elements whose index is between
727 jsr166 1.25 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
728 dl 1.1 * Shifts any succeeding elements to the left (reduces their index).
729 jsr166 1.25 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
730     * (If {@code toIndex==fromIndex}, this operation has no effect.)
731 dl 1.1 *
732 jsr166 1.25 * @throws IndexOutOfBoundsException if {@code fromIndex} or
733     * {@code toIndex} is out of range
734     * ({@code fromIndex < 0 ||
735     * toIndex > size() ||
736     * toIndex < fromIndex})
737 dl 1.1 */
738     protected void removeRange(int fromIndex, int toIndex) {
739 jsr166 1.33 if (fromIndex > toIndex) {
740     throw new IndexOutOfBoundsException(
741     outOfBoundsMsg(fromIndex, toIndex));
742     }
743 jsr166 1.26 modCount++;
744 jsr166 1.47 shiftTailOverGap(elementData, fromIndex, toIndex);
745 jsr166 1.41 // checkInvariants();
746 jsr166 1.25 }
747    
748 jsr166 1.47 /** 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 jsr166 1.25 /**
756     * A version of rangeCheck used by add and addAll.
757     */
758     private void rangeCheckForAdd(int index) {
759 jsr166 1.26 if (index > size || index < 0)
760     throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
761 jsr166 1.25 }
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 jsr166 1.26 return "Index: "+index+", Size: "+size;
770 jsr166 1.25 }
771    
772     /**
773 jsr166 1.33 * 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 jsr166 1.25 * 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 jsr166 1.33 * is incompatible with the specified collection
787     * (<a href="Collection.html#optional-restrictions">optional</a>)
788 jsr166 1.25 * @throws NullPointerException if this list contains a null element and the
789 jsr166 1.33 * specified collection does not permit null elements
790     * (<a href="Collection.html#optional-restrictions">optional</a>),
791 jsr166 1.25 * or if the specified collection is null
792     * @see Collection#contains(Object)
793     */
794     public boolean removeAll(Collection<?> c) {
795 jsr166 1.40 return batchRemove(c, false, 0, size);
796 jsr166 1.25 }
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 jsr166 1.33 * is incompatible with the specified collection
807     * (<a href="Collection.html#optional-restrictions">optional</a>)
808 jsr166 1.25 * @throws NullPointerException if this list contains a null element and the
809 jsr166 1.33 * specified collection does not permit null elements
810     * (<a href="Collection.html#optional-restrictions">optional</a>),
811 jsr166 1.25 * or if the specified collection is null
812     * @see Collection#contains(Object)
813     */
814     public boolean retainAll(Collection<?> c) {
815 jsr166 1.40 return batchRemove(c, true, 0, size);
816 jsr166 1.25 }
817    
818 jsr166 1.40 boolean batchRemove(Collection<?> c, boolean complement,
819     final int from, final int end) {
820 jsr166 1.37 Objects.requireNonNull(c);
821     final Object[] es = elementData;
822     int r;
823     // Optimize for initial run of survivors
824 jsr166 1.53 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 jsr166 1.26 }
845 jsr166 1.41 // checkInvariants();
846 jsr166 1.53 return true;
847 jsr166 1.25 }
848    
849     /**
850 jsr166 1.46 * Saves the state of the {@code ArrayList} instance to a stream
851     * (that is, serializes it).
852 dl 1.1 *
853 jsr166 1.46 * @param s the stream
854     * @throws java.io.IOException if an I/O error occurs
855 jsr166 1.33 * @serialData The length of the array backing the {@code ArrayList}
856 dl 1.1 * instance is emitted (int), followed by all of its elements
857 jsr166 1.33 * (each an {@code Object}) in the proper order.
858 dl 1.1 */
859 jsr166 1.69 // OPENJDK @java.io.Serial
860 dl 1.1 private void writeObject(java.io.ObjectOutputStream s)
861 jsr166 1.46 throws java.io.IOException {
862 jsr166 1.26 // Write out element count, and any hidden stuff
863     int expectedModCount = modCount;
864     s.defaultWriteObject();
865 dl 1.1
866 jsr166 1.52 // Write out size as capacity for behavioral compatibility with clone()
867 jsr166 1.33 s.writeInt(size);
868 dl 1.1
869 jsr166 1.26 // Write out all elements in the proper order.
870 jsr166 1.33 for (int i=0; i<size; i++) {
871 dl 1.1 s.writeObject(elementData[i]);
872 jsr166 1.33 }
873 dl 1.1
874 jsr166 1.26 if (modCount != expectedModCount) {
875 dl 1.1 throw new ConcurrentModificationException();
876     }
877     }
878    
879     /**
880 jsr166 1.46 * 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 dl 1.1 */
887 jsr166 1.69 // OPENJDK @java.io.Serial
888 dl 1.1 private void readObject(java.io.ObjectInputStream s)
889     throws java.io.IOException, ClassNotFoundException {
890 jsr166 1.33
891 jsr166 1.26 // Read in size, and any hidden stuff
892     s.defaultReadObject();
893 dl 1.1
894 jsr166 1.33 // Read in capacity
895     s.readInt(); // ignored
896    
897     if (size > 0) {
898     // like clone(), allocate array based upon size not capacity
899 jsr166 1.65 jsr166.Platform.checkArray(s, Object[].class, size);
900 jsr166 1.33 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 dl 1.1 }
914 jsr166 1.25
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 jsr166 1.33 rangeCheckForAdd(index);
929 jsr166 1.26 return new ListItr(index);
930 jsr166 1.25 }
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 jsr166 1.26 return new ListItr(0);
942 jsr166 1.25 }
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 jsr166 1.26 return new Itr();
953 jsr166 1.25 }
954    
955     /**
956     * An optimized version of AbstractList.Itr
957     */
958     private class Itr implements Iterator<E> {
959 jsr166 1.26 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 jsr166 1.25
963 jsr166 1.33 // prevent creating a synthetic constructor
964     Itr() {}
965    
966 jsr166 1.26 public boolean hasNext() {
967 jsr166 1.25 return cursor != size;
968 jsr166 1.26 }
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 jsr166 1.25
983 jsr166 1.26 public void remove() {
984     if (lastRet < 0)
985     throw new IllegalStateException();
986 jsr166 1.25 checkForComodification();
987 jsr166 1.26
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 jsr166 1.33 @Override
999 jsr166 1.44 public void forEachRemaining(Consumer<? super E> action) {
1000     Objects.requireNonNull(action);
1001 jsr166 1.33 final int size = ArrayList.this.size;
1002     int i = cursor;
1003 jsr166 1.44 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 jsr166 1.33 }
1014     }
1015    
1016 jsr166 1.26 final void checkForComodification() {
1017     if (modCount != expectedModCount)
1018     throw new ConcurrentModificationException();
1019     }
1020 jsr166 1.25 }
1021    
1022     /**
1023     * An optimized version of AbstractList.ListItr
1024     */
1025     private class ListItr extends Itr implements ListIterator<E> {
1026 jsr166 1.26 ListItr(int index) {
1027     super();
1028     cursor = index;
1029     }
1030    
1031     public boolean hasPrevious() {
1032     return cursor != 0;
1033     }
1034 jsr166 1.25
1035 jsr166 1.26 public int nextIndex() {
1036     return cursor;
1037     }
1038    
1039     public int previousIndex() {
1040     return cursor - 1;
1041     }
1042    
1043     @SuppressWarnings("unchecked")
1044 jsr166 1.25 public E previous() {
1045 jsr166 1.26 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 jsr166 1.25 }
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 jsr166 1.26 subListRangeCheck(fromIndex, toIndex, size);
1114 jsr166 1.33 return new SubList<>(this, fromIndex, toIndex);
1115 jsr166 1.25 }
1116    
1117 jsr166 1.33 private static class SubList<E> extends AbstractList<E> implements RandomAccess {
1118     private final ArrayList<E> root;
1119     private final SubList<E> parent;
1120 jsr166 1.26 private final int offset;
1121 jsr166 1.33 private int size;
1122 jsr166 1.26
1123 jsr166 1.33 /**
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 jsr166 1.26 this.parent = parent;
1140 jsr166 1.33 this.offset = parent.offset + fromIndex;
1141 jsr166 1.26 this.size = toIndex - fromIndex;
1142 jsr166 1.70 this.modCount = parent.modCount;
1143 jsr166 1.26 }
1144    
1145 jsr166 1.33 public E set(int index, E element) {
1146     Objects.checkIndex(index, size);
1147 jsr166 1.26 checkForComodification();
1148 jsr166 1.33 E oldValue = root.elementData(offset + index);
1149     root.elementData[offset + index] = element;
1150 jsr166 1.26 return oldValue;
1151     }
1152    
1153     public E get(int index) {
1154 jsr166 1.33 Objects.checkIndex(index, size);
1155 jsr166 1.26 checkForComodification();
1156 jsr166 1.33 return root.elementData(offset + index);
1157 jsr166 1.26 }
1158    
1159     public int size() {
1160     checkForComodification();
1161 jsr166 1.33 return size;
1162 jsr166 1.26 }
1163    
1164 jsr166 1.33 public void add(int index, E element) {
1165 jsr166 1.26 rangeCheckForAdd(index);
1166     checkForComodification();
1167 jsr166 1.33 root.add(offset + index, element);
1168     updateSizeAndModCount(1);
1169 jsr166 1.26 }
1170    
1171     public E remove(int index) {
1172 jsr166 1.33 Objects.checkIndex(index, size);
1173 jsr166 1.26 checkForComodification();
1174 jsr166 1.33 E result = root.remove(offset + index);
1175     updateSizeAndModCount(-1);
1176 jsr166 1.26 return result;
1177     }
1178    
1179     protected void removeRange(int fromIndex, int toIndex) {
1180     checkForComodification();
1181 jsr166 1.33 root.removeRange(offset + fromIndex, offset + toIndex);
1182     updateSizeAndModCount(fromIndex - toIndex);
1183 jsr166 1.26 }
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 jsr166 1.33 root.addAll(offset + index, c);
1196     updateSizeAndModCount(cSize);
1197 jsr166 1.26 return true;
1198     }
1199    
1200 jsr166 1.58 public void replaceAll(UnaryOperator<E> operator) {
1201     root.replaceAllRange(operator, offset, offset + size);
1202     }
1203    
1204 jsr166 1.40 public boolean removeAll(Collection<?> c) {
1205     return batchRemove(c, false);
1206     }
1207 jsr166 1.41
1208 jsr166 1.40 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 jsr166 1.56 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 jsr166 1.60 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 jsr166 1.26 public Iterator<E> iterator() {
1285     return listIterator();
1286     }
1287    
1288 jsr166 1.33 public ListIterator<E> listIterator(int index) {
1289 jsr166 1.26 checkForComodification();
1290     rangeCheckForAdd(index);
1291    
1292     return new ListIterator<E>() {
1293     int cursor = index;
1294     int lastRet = -1;
1295 jsr166 1.70 int expectedModCount = SubList.this.modCount;
1296 jsr166 1.26
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 jsr166 1.33 Object[] elementData = root.elementData;
1308 jsr166 1.26 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 jsr166 1.33 Object[] elementData = root.elementData;
1325 jsr166 1.26 if (offset + i >= elementData.length)
1326     throw new ConcurrentModificationException();
1327     cursor = i;
1328     return (E) elementData[offset + (lastRet = i)];
1329     }
1330    
1331 jsr166 1.44 public void forEachRemaining(Consumer<? super E> action) {
1332     Objects.requireNonNull(action);
1333 jsr166 1.33 final int size = SubList.this.size;
1334     int i = cursor;
1335 jsr166 1.44 if (i < size) {
1336     final Object[] es = root.elementData;
1337     if (offset + i >= es.length)
1338     throw new ConcurrentModificationException();
1339 jsr166 1.70 for (; i < size && root.modCount == expectedModCount; i++)
1340 jsr166 1.44 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 jsr166 1.33 }
1346     }
1347    
1348 jsr166 1.26 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 jsr166 1.70 expectedModCount = SubList.this.modCount;
1366 jsr166 1.26 } 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 jsr166 1.33 root.set(offset + lastRet, e);
1378 jsr166 1.26 } 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 jsr166 1.70 expectedModCount = SubList.this.modCount;
1392 jsr166 1.26 } catch (IndexOutOfBoundsException ex) {
1393     throw new ConcurrentModificationException();
1394     }
1395     }
1396    
1397     final void checkForComodification() {
1398 jsr166 1.33 if (root.modCount != expectedModCount)
1399 jsr166 1.26 throw new ConcurrentModificationException();
1400     }
1401     };
1402     }
1403    
1404     public List<E> subList(int fromIndex, int toIndex) {
1405     subListRangeCheck(fromIndex, toIndex, size);
1406 jsr166 1.33 return new SubList<>(this, fromIndex, toIndex);
1407 jsr166 1.26 }
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 jsr166 1.33 if (root.modCount != modCount)
1420 jsr166 1.26 throw new ConcurrentModificationException();
1421     }
1422 jsr166 1.33
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 jsr166 1.45 // ArrayListSpliterator not used here due to late-binding
1436     return new Spliterator<E>() {
1437 jsr166 1.33 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 jsr166 1.45 public ArrayList<E>.ArrayListSpliterator trySplit() {
1451 jsr166 1.33 int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1452 jsr166 1.45 // ArrayListSpliterator can be used here as the source is already bound
1453 jsr166 1.33 return (lo >= mid) ? null : // divide range in half unless too small
1454 jsr166 1.45 root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
1455 jsr166 1.33 }
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 jsr166 1.45 return getFence() - index;
1497 jsr166 1.33 }
1498    
1499     public int characteristics() {
1500     return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1501     }
1502     };
1503     }
1504     }
1505    
1506 jsr166 1.48 /**
1507     * @throws NullPointerException {@inheritDoc}
1508     */
1509 jsr166 1.33 @Override
1510     public void forEach(Consumer<? super E> action) {
1511     Objects.requireNonNull(action);
1512     final int expectedModCount = modCount;
1513 jsr166 1.39 final Object[] es = elementData;
1514 jsr166 1.33 final int size = this.size;
1515 jsr166 1.41 for (int i = 0; modCount == expectedModCount && i < size; i++)
1516 jsr166 1.39 action.accept(elementAt(es, i));
1517 jsr166 1.41 if (modCount != expectedModCount)
1518 jsr166 1.33 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 jsr166 1.45 return new ArrayListSpliterator(0, -1, 0);
1537 jsr166 1.33 }
1538    
1539     /** Index-based split-by-two, lazily initialized Spliterator */
1540 jsr166 1.45 final class ArrayListSpliterator implements Spliterator<E> {
1541 jsr166 1.33
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 jsr166 1.49 /** Creates new spliterator covering the given range. */
1579 jsr166 1.45 ArrayListSpliterator(int origin, int fence, int expectedModCount) {
1580 jsr166 1.33 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 jsr166 1.45 expectedModCount = modCount;
1589     hi = fence = size;
1590 jsr166 1.33 }
1591     return hi;
1592     }
1593    
1594 jsr166 1.45 public ArrayListSpliterator trySplit() {
1595 jsr166 1.33 int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
1596     return (lo >= mid) ? null : // divide range in half unless too small
1597 jsr166 1.45 new ArrayListSpliterator(lo, index = mid, expectedModCount);
1598 jsr166 1.33 }
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 jsr166 1.45 @SuppressWarnings("unchecked") E e = (E)elementData[i];
1607 jsr166 1.33 action.accept(e);
1608 jsr166 1.45 if (modCount != expectedModCount)
1609 jsr166 1.33 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 jsr166 1.45 Object[] a;
1618 jsr166 1.33 if (action == null)
1619     throw new NullPointerException();
1620 jsr166 1.45 if ((a = elementData) != null) {
1621 jsr166 1.33 if ((hi = fence) < 0) {
1622 jsr166 1.45 mc = modCount;
1623     hi = size;
1624 jsr166 1.33 }
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 jsr166 1.45 if (modCount == mc)
1633 jsr166 1.33 return;
1634     }
1635     }
1636     throw new ConcurrentModificationException();
1637     }
1638    
1639     public long estimateSize() {
1640 jsr166 1.45 return getFence() - index;
1641 jsr166 1.33 }
1642    
1643     public int characteristics() {
1644     return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1645     }
1646     }
1647    
1648 jsr166 1.39 // 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 jsr166 1.48 /**
1661     * @throws NullPointerException {@inheritDoc}
1662     */
1663 jsr166 1.33 @Override
1664 jsr166 1.40 public boolean removeIf(Predicate<? super E> filter) {
1665     return removeIf(filter, 0, size);
1666     }
1667    
1668 jsr166 1.43 /**
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 jsr166 1.33 Objects.requireNonNull(filter);
1674 jsr166 1.36 int expectedModCount = modCount;
1675     final Object[] es = elementData;
1676 jsr166 1.37 // Optimize for initial run of survivors
1677 jsr166 1.43 for (; i < end && !filter.test(elementAt(es, i)); i++)
1678 jsr166 1.38 ;
1679 jsr166 1.39 // 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 jsr166 1.43 if (i < end) {
1683 jsr166 1.39 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 jsr166 1.40 if (modCount != expectedModCount)
1690     throw new ConcurrentModificationException();
1691 jsr166 1.43 modCount++;
1692 jsr166 1.39 int w = beg;
1693     for (i = beg; i < end; i++)
1694     if (isClear(deathRow, i - beg))
1695     es[w++] = es[i];
1696 jsr166 1.47 shiftTailOverGap(es, w, end);
1697 jsr166 1.43 // checkInvariants();
1698     return true;
1699     } else {
1700     if (modCount != expectedModCount)
1701     throw new ConcurrentModificationException();
1702     // checkInvariants();
1703     return false;
1704 jsr166 1.33 }
1705     }
1706    
1707     @Override
1708     public void replaceAll(UnaryOperator<E> operator) {
1709 jsr166 1.58 replaceAllRange(operator, 0, size);
1710 jsr166 1.66 // TODO(8203662): remove increment of modCount from ...
1711     modCount++;
1712 jsr166 1.58 }
1713    
1714 jsr166 1.59 private void replaceAllRange(UnaryOperator<E> operator, int i, int end) {
1715 jsr166 1.33 Objects.requireNonNull(operator);
1716     final int expectedModCount = modCount;
1717 jsr166 1.39 final Object[] es = elementData;
1718 jsr166 1.59 for (; modCount == expectedModCount && i < end; i++)
1719 jsr166 1.39 es[i] = operator.apply(elementAt(es, i));
1720 jsr166 1.41 if (modCount != expectedModCount)
1721 jsr166 1.33 throw new ConcurrentModificationException();
1722 jsr166 1.41 // checkInvariants();
1723 jsr166 1.33 }
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 jsr166 1.41 if (modCount != expectedModCount)
1731 jsr166 1.33 throw new ConcurrentModificationException();
1732     modCount++;
1733 jsr166 1.41 // checkInvariants();
1734     }
1735    
1736     void checkInvariants() {
1737     // assert size >= 0;
1738     // assert size == elementData.length || elementData[size] == null;
1739 jsr166 1.25 }
1740 dl 1.1 }