ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayList.java
Revision: 1.68
Committed: Sat Aug 10 16:48:05 2019 UTC (4 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.67: +1 -1 lines
Log Message:
drop support for jdk9 and jdk10; drop backward compatibility hacks

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