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

File Contents

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