[cvs] / jsr166 / src / jdk8 / java / util / ArrayList.java Repository:
ViewVC logotype

Annotation of /jsr166/src/jdk8/java/util/ArrayList.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.3 - (view) (download)

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

Doug Lea
ViewVC Help
Powered by ViewVC 1.0.8