18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 */
24
25 /*
26 * Written by Doug Lea with assistance from members of JCP JSR-166
27 * Expert Group. Adapted and released, under explicit permission,
28 * from JDK ArrayList.java which carries the following copyright:
29 *
30 * Copyright 1997 by Sun Microsystems, Inc.,
31 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
32 * All rights reserved.
33 */
34
35 package java.util.concurrent;
36
37 import java.lang.reflect.Field;
38 import java.util.AbstractList;
39 import java.util.Arrays;
40 import java.util.Collection;
41 import java.util.Comparator;
42 import java.util.ConcurrentModificationException;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.ListIterator;
46 import java.util.NoSuchElementException;
47 import java.util.Objects;
48 import java.util.RandomAccess;
49 import java.util.Spliterator;
50 import java.util.Spliterators;
51 import java.util.function.Consumer;
52 import java.util.function.Predicate;
53 import java.util.function.UnaryOperator;
54 import jdk.internal.misc.SharedSecrets;
55
56 /**
57 * A thread-safe variant of {@link java.util.ArrayList} in which all mutative
58 * operations ({@code add}, {@code set}, and so on) are implemented by
117 final void setArray(Object[] a) {
118 array = a;
119 }
120
121 /**
122 * Creates an empty list.
123 */
124 public CopyOnWriteArrayList() {
125 setArray(new Object[0]);
126 }
127
128 /**
129 * Creates a list containing the elements of the specified
130 * collection, in the order they are returned by the collection's
131 * iterator.
132 *
133 * @param c the collection of initially held elements
134 * @throws NullPointerException if the specified collection is null
135 */
136 public CopyOnWriteArrayList(Collection<? extends E> c) {
137 Object[] elements;
138 if (c.getClass() == CopyOnWriteArrayList.class)
139 elements = ((CopyOnWriteArrayList<?>)c).getArray();
140 else {
141 elements = c.toArray();
142 // defend against c.toArray (incorrectly) not returning Object[]
143 // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
144 if (elements.getClass() != Object[].class)
145 elements = Arrays.copyOf(elements, elements.length, Object[].class);
146 }
147 setArray(elements);
148 }
149
150 /**
151 * Creates a list holding a copy of the given array.
152 *
153 * @param toCopyIn the array (a copy of this array is used as the
154 * internal array)
155 * @throws NullPointerException if the specified array is null
156 */
157 public CopyOnWriteArrayList(E[] toCopyIn) {
158 setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
159 }
160
161 /**
162 * Returns the number of elements in this list.
163 *
164 * @return the number of elements in this list
165 */
166 public int size() {
167 return getArray().length;
168 }
169
170 /**
171 * Returns {@code true} if this list contains no elements.
172 *
173 * @return {@code true} if this list contains no elements
174 */
175 public boolean isEmpty() {
176 return size() == 0;
177 }
178
179 /**
180 * static version of indexOf, to allow repeated calls without
181 * needing to re-acquire array each time.
182 * @param o element to search for
183 * @param elements the array
184 * @param index first index to search
185 * @param fence one past last index to search
186 * @return index of element, or -1 if absent
187 */
188 private static int indexOf(Object o, Object[] elements,
189 int index, int fence) {
190 if (o == null) {
191 for (int i = index; i < fence; i++)
192 if (elements[i] == null)
193 return i;
194 } else {
195 for (int i = index; i < fence; i++)
196 if (o.equals(elements[i]))
197 return i;
198 }
199 return -1;
200 }
201
202 /**
203 * static version of lastIndexOf.
204 * @param o element to search for
205 * @param elements the array
206 * @param index first index to search
207 * @return index of element, or -1 if absent
208 */
209 private static int lastIndexOf(Object o, Object[] elements, int index) {
210 if (o == null) {
211 for (int i = index; i >= 0; i--)
212 if (elements[i] == null)
213 return i;
214 } else {
215 for (int i = index; i >= 0; i--)
216 if (o.equals(elements[i]))
217 return i;
218 }
219 return -1;
220 }
221
222 /**
223 * Returns {@code true} if this list contains the specified element.
224 * More formally, returns {@code true} if and only if this list contains
225 * at least one element {@code e} such that {@code Objects.equals(o, e)}.
226 *
227 * @param o element whose presence in this list is to be tested
228 * @return {@code true} if this list contains the specified element
229 */
230 public boolean contains(Object o) {
231 Object[] elements = getArray();
232 return indexOf(o, elements, 0, elements.length) >= 0;
233 }
234
235 /**
236 * {@inheritDoc}
237 */
238 public int indexOf(Object o) {
239 Object[] elements = getArray();
240 return indexOf(o, elements, 0, elements.length);
241 }
242
243 /**
244 * Returns the index of the first occurrence of the specified element in
245 * this list, searching forwards from {@code index}, or returns -1 if
246 * the element is not found.
247 * More formally, returns the lowest index {@code i} such that
248 * {@code i >= index && Objects.equals(get(i), e)},
249 * or -1 if there is no such index.
250 *
251 * @param e element to search for
252 * @param index index to start searching from
253 * @return the index of the first occurrence of the element in
254 * this list at position {@code index} or later in the list;
255 * {@code -1} if the element is not found.
256 * @throws IndexOutOfBoundsException if the specified index is negative
257 */
258 public int indexOf(E e, int index) {
259 Object[] elements = getArray();
260 return indexOf(e, elements, index, elements.length);
261 }
262
263 /**
264 * {@inheritDoc}
265 */
266 public int lastIndexOf(Object o) {
267 Object[] elements = getArray();
268 return lastIndexOf(o, elements, elements.length - 1);
269 }
270
271 /**
272 * Returns the index of the last occurrence of the specified element in
273 * this list, searching backwards from {@code index}, or returns -1 if
274 * the element is not found.
275 * More formally, returns the highest index {@code i} such that
276 * {@code i <= index && Objects.equals(get(i), e)},
277 * or -1 if there is no such index.
278 *
279 * @param e element to search for
280 * @param index index to start searching backwards from
281 * @return the index of the last occurrence of the element at position
282 * less than or equal to {@code index} in this list;
283 * -1 if the element is not found.
284 * @throws IndexOutOfBoundsException if the specified index is greater
285 * than or equal to the current size of this list
286 */
287 public int lastIndexOf(E e, int index) {
288 Object[] elements = getArray();
289 return lastIndexOf(e, elements, index);
290 }
291
292 /**
293 * Returns a shallow copy of this list. (The elements themselves
294 * are not copied.)
295 *
296 * @return a clone of this list
297 */
298 public Object clone() {
299 try {
300 @SuppressWarnings("unchecked")
301 CopyOnWriteArrayList<E> clone =
302 (CopyOnWriteArrayList<E>) super.clone();
303 clone.resetLock();
304 return clone;
305 } catch (CloneNotSupportedException e) {
306 // this shouldn't happen, since we are Cloneable
307 throw new InternalError();
308 }
309 }
310
311 /**
312 * Returns an array containing all of the elements in this list
313 * in proper sequence (from first to last element).
314 *
315 * <p>The returned array will be "safe" in that no references to it are
316 * maintained by this list. (In other words, this method must allocate
317 * a new array). The caller is thus free to modify the returned array.
318 *
319 * <p>This method acts as bridge between array-based and collection-based
320 * APIs.
321 *
322 * @return an array containing all the elements in this list
323 */
324 public Object[] toArray() {
325 Object[] elements = getArray();
326 return Arrays.copyOf(elements, elements.length);
327 }
328
329 /**
330 * Returns an array containing all of the elements in this list in
331 * proper sequence (from first to last element); the runtime type of
332 * the returned array is that of the specified array. If the list fits
333 * in the specified array, it is returned therein. Otherwise, a new
334 * array is allocated with the runtime type of the specified array and
335 * the size of this list.
336 *
337 * <p>If this list fits in the specified array with room to spare
338 * (i.e., the array has more elements than this list), the element in
339 * the array immediately following the end of the list is set to
340 * {@code null}. (This is useful in determining the length of this
341 * list <i>only</i> if the caller knows that this list does not contain
342 * any null elements.)
343 *
344 * <p>Like the {@link #toArray()} method, this method acts as bridge between
345 * array-based and collection-based APIs. Further, this method allows
346 * precise control over the runtime type of the output array, and may,
349 * <p>Suppose {@code x} is a list known to contain only strings.
350 * The following code can be used to dump the list into a newly
351 * allocated array of {@code String}:
352 *
353 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
354 *
355 * Note that {@code toArray(new Object[0])} is identical in function to
356 * {@code toArray()}.
357 *
358 * @param a the array into which the elements of the list are to
359 * be stored, if it is big enough; otherwise, a new array of the
360 * same runtime type is allocated for this purpose.
361 * @return an array containing all the elements in this list
362 * @throws ArrayStoreException if the runtime type of the specified array
363 * is not a supertype of the runtime type of every element in
364 * this list
365 * @throws NullPointerException if the specified array is null
366 */
367 @SuppressWarnings("unchecked")
368 public <T> T[] toArray(T[] a) {
369 Object[] elements = getArray();
370 int len = elements.length;
371 if (a.length < len)
372 return (T[]) Arrays.copyOf(elements, len, a.getClass());
373 else {
374 System.arraycopy(elements, 0, a, 0, len);
375 if (a.length > len)
376 a[len] = null;
377 return a;
378 }
379 }
380
381 // Positional Access Operations
382
383 @SuppressWarnings("unchecked")
384 static <E> E elementAt(Object[] a, int index) {
385 return (E) a[index];
386 }
387
388 static String outOfBounds(int index, int size) {
389 return "Index: " + index + ", Size: " + size;
390 }
391
392 /**
393 * {@inheritDoc}
394 *
395 * @throws IndexOutOfBoundsException {@inheritDoc}
396 */
397 public E get(int index) {
398 return elementAt(getArray(), index);
399 }
400
401 /**
402 * Replaces the element at the specified position in this list with the
403 * specified element.
404 *
405 * @throws IndexOutOfBoundsException {@inheritDoc}
406 */
407 public E set(int index, E element) {
408 synchronized (lock) {
409 Object[] elements = getArray();
410 E oldValue = elementAt(elements, index);
411
412 if (oldValue != element) {
413 int len = elements.length;
414 Object[] newElements = Arrays.copyOf(elements, len);
415 newElements[index] = element;
416 setArray(newElements);
417 } else {
418 // Not quite a no-op; ensures volatile write semantics
419 setArray(elements);
420 }
421 return oldValue;
422 }
423 }
424
425 /**
426 * Appends the specified element to the end of this list.
427 *
428 * @param e element to be appended to this list
429 * @return {@code true} (as specified by {@link Collection#add})
430 */
431 public boolean add(E e) {
432 synchronized (lock) {
433 Object[] elements = getArray();
434 int len = elements.length;
435 Object[] newElements = Arrays.copyOf(elements, len + 1);
436 newElements[len] = e;
437 setArray(newElements);
438 return true;
439 }
440 }
441
442 /**
443 * Inserts the specified element at the specified position in this
444 * list. Shifts the element currently at that position (if any) and
445 * any subsequent elements to the right (adds one to their indices).
446 *
447 * @throws IndexOutOfBoundsException {@inheritDoc}
448 */
449 public void add(int index, E element) {
450 synchronized (lock) {
451 Object[] elements = getArray();
452 int len = elements.length;
453 if (index > len || index < 0)
454 throw new IndexOutOfBoundsException(outOfBounds(index, len));
455 Object[] newElements;
456 int numMoved = len - index;
457 if (numMoved == 0)
458 newElements = Arrays.copyOf(elements, len + 1);
459 else {
460 newElements = new Object[len + 1];
461 System.arraycopy(elements, 0, newElements, 0, index);
462 System.arraycopy(elements, index, newElements, index + 1,
463 numMoved);
464 }
465 newElements[index] = element;
466 setArray(newElements);
467 }
468 }
469
470 /**
471 * Removes the element at the specified position in this list.
472 * Shifts any subsequent elements to the left (subtracts one from their
473 * indices). Returns the element that was removed from the list.
474 *
475 * @throws IndexOutOfBoundsException {@inheritDoc}
476 */
477 public E remove(int index) {
478 synchronized (lock) {
479 Object[] elements = getArray();
480 int len = elements.length;
481 E oldValue = elementAt(elements, index);
482 int numMoved = len - index - 1;
483 if (numMoved == 0)
484 setArray(Arrays.copyOf(elements, len - 1));
485 else {
486 Object[] newElements = new Object[len - 1];
487 System.arraycopy(elements, 0, newElements, 0, index);
488 System.arraycopy(elements, index + 1, newElements, index,
489 numMoved);
490 setArray(newElements);
491 }
492 return oldValue;
493 }
494 }
495
496 /**
497 * Removes the first occurrence of the specified element from this list,
498 * if it is present. If this list does not contain the element, it is
499 * unchanged. More formally, removes the element with the lowest index
500 * {@code i} such that {@code Objects.equals(o, get(i))}
501 * (if such an element exists). Returns {@code true} if this list
502 * contained the specified element (or equivalently, if this list
503 * changed as a result of the call).
504 *
505 * @param o element to be removed from this list, if present
506 * @return {@code true} if this list contained the specified element
507 */
508 public boolean remove(Object o) {
509 Object[] snapshot = getArray();
510 int index = indexOf(o, snapshot, 0, snapshot.length);
511 return index >= 0 && remove(o, snapshot, index);
512 }
513
514 /**
515 * A version of remove(Object) using the strong hint that given
516 * recent snapshot contains o at the given index.
517 */
518 private boolean remove(Object o, Object[] snapshot, int index) {
519 synchronized (lock) {
520 Object[] current = getArray();
521 int len = current.length;
522 if (snapshot != current) findIndex: {
523 int prefix = Math.min(index, len);
524 for (int i = 0; i < prefix; i++) {
525 if (current[i] != snapshot[i]
526 && Objects.equals(o, current[i])) {
527 index = i;
528 break findIndex;
529 }
530 }
531 if (index >= len)
532 return false;
533 if (current[index] == o)
534 break findIndex;
535 index = indexOf(o, current, index, len);
536 if (index < 0)
537 return false;
538 }
539 Object[] newElements = new Object[len - 1];
540 System.arraycopy(current, 0, newElements, 0, index);
541 System.arraycopy(current, index + 1,
542 newElements, index,
543 len - index - 1);
544 setArray(newElements);
545 return true;
546 }
547 }
548
549 /**
550 * Removes from this list all of the elements whose index is between
551 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
552 * Shifts any succeeding elements to the left (reduces their index).
553 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
554 * (If {@code toIndex==fromIndex}, this operation has no effect.)
555 *
556 * @param fromIndex index of first element to be removed
557 * @param toIndex index after last element to be removed
558 * @throws IndexOutOfBoundsException if fromIndex or toIndex out of range
559 * ({@code fromIndex < 0 || toIndex > size() || toIndex < fromIndex})
560 */
561 void removeRange(int fromIndex, int toIndex) {
562 synchronized (lock) {
563 Object[] elements = getArray();
564 int len = elements.length;
565
566 if (fromIndex < 0 || toIndex > len || toIndex < fromIndex)
567 throw new IndexOutOfBoundsException();
568 int newlen = len - (toIndex - fromIndex);
569 int numMoved = len - toIndex;
570 if (numMoved == 0)
571 setArray(Arrays.copyOf(elements, newlen));
572 else {
573 Object[] newElements = new Object[newlen];
574 System.arraycopy(elements, 0, newElements, 0, fromIndex);
575 System.arraycopy(elements, toIndex, newElements,
576 fromIndex, numMoved);
577 setArray(newElements);
578 }
579 }
580 }
581
582 /**
583 * Appends the element, if not present.
584 *
585 * @param e element to be added to this list, if absent
586 * @return {@code true} if the element was added
587 */
588 public boolean addIfAbsent(E e) {
589 Object[] snapshot = getArray();
590 return indexOf(e, snapshot, 0, snapshot.length) < 0
591 && addIfAbsent(e, snapshot);
592 }
593
594 /**
595 * A version of addIfAbsent using the strong hint that given
596 * recent snapshot does not contain e.
597 */
598 private boolean addIfAbsent(E e, Object[] snapshot) {
599 synchronized (lock) {
600 Object[] current = getArray();
601 int len = current.length;
602 if (snapshot != current) {
603 // Optimize for lost race to another addXXX operation
604 int common = Math.min(snapshot.length, len);
605 for (int i = 0; i < common; i++)
606 if (current[i] != snapshot[i]
607 && Objects.equals(e, current[i]))
608 return false;
609 if (indexOf(e, current, common, len) >= 0)
610 return false;
611 }
612 Object[] newElements = Arrays.copyOf(current, len + 1);
613 newElements[len] = e;
614 setArray(newElements);
615 return true;
616 }
617 }
618
619 /**
620 * Returns {@code true} if this list contains all of the elements of the
621 * specified collection.
622 *
623 * @param c collection to be checked for containment in this list
624 * @return {@code true} if this list contains all of the elements of the
625 * specified collection
626 * @throws NullPointerException if the specified collection is null
627 * @see #contains(Object)
628 */
629 public boolean containsAll(Collection<?> c) {
630 Object[] elements = getArray();
631 int len = elements.length;
632 for (Object e : c) {
633 if (indexOf(e, elements, 0, len) < 0)
634 return false;
635 }
636 return true;
637 }
638
639 /**
640 * Removes from this list all of its elements that are contained in
641 * the specified collection. This is a particularly expensive operation
642 * in this class because of the need for an internal temporary array.
643 *
644 * @param c collection containing elements to be removed from this list
645 * @return {@code true} if this list changed as a result of the call
646 * @throws ClassCastException if the class of an element of this list
647 * is incompatible with the specified collection
648 * (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
649 * @throws NullPointerException if this list contains a null element and the
650 * specified collection does not permit null elements
651 * (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>),
652 * or if the specified collection is null
653 * @see #remove(Object)
677 Objects.requireNonNull(c);
678 return bulkRemove(e -> !c.contains(e));
679 }
680
681 /**
682 * Appends all of the elements in the specified collection that
683 * are not already contained in this list, to the end of
684 * this list, in the order that they are returned by the
685 * specified collection's iterator.
686 *
687 * @param c collection containing elements to be added to this list
688 * @return the number of elements added
689 * @throws NullPointerException if the specified collection is null
690 * @see #addIfAbsent(Object)
691 */
692 public int addAllAbsent(Collection<? extends E> c) {
693 Object[] cs = c.toArray();
694 if (cs.length == 0)
695 return 0;
696 synchronized (lock) {
697 Object[] elements = getArray();
698 int len = elements.length;
699 int added = 0;
700 // uniquify and compact elements in cs
701 for (int i = 0; i < cs.length; ++i) {
702 Object e = cs[i];
703 if (indexOf(e, elements, 0, len) < 0 &&
704 indexOf(e, cs, 0, added) < 0)
705 cs[added++] = e;
706 }
707 if (added > 0) {
708 Object[] newElements = Arrays.copyOf(elements, len + added);
709 System.arraycopy(cs, 0, newElements, len, added);
710 setArray(newElements);
711 }
712 return added;
713 }
714 }
715
716 /**
717 * Removes all of the elements from this list.
718 * The list will be empty after this call returns.
719 */
720 public void clear() {
721 synchronized (lock) {
722 setArray(new Object[0]);
723 }
724 }
725
726 /**
727 * Appends all of the elements in the specified collection to the end
728 * of this list, in the order that they are returned by the specified
729 * collection's iterator.
730 *
731 * @param c collection containing elements to be added to this list
732 * @return {@code true} if this list changed as a result of the call
733 * @throws NullPointerException if the specified collection is null
734 * @see #add(Object)
735 */
736 public boolean addAll(Collection<? extends E> c) {
737 Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
738 ((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
739 if (cs.length == 0)
740 return false;
741 synchronized (lock) {
742 Object[] elements = getArray();
743 int len = elements.length;
744 if (len == 0 && cs.getClass() == Object[].class)
745 setArray(cs);
746 else {
747 Object[] newElements = Arrays.copyOf(elements, len + cs.length);
748 System.arraycopy(cs, 0, newElements, len, cs.length);
749 setArray(newElements);
750 }
751 return true;
752 }
753 }
754
755 /**
756 * Inserts all of the elements in the specified collection into this
757 * list, starting at the specified position. Shifts the element
758 * currently at that position (if any) and any subsequent elements to
759 * the right (increases their indices). The new elements will appear
760 * in this list in the order that they are returned by the
761 * specified collection's iterator.
762 *
763 * @param index index at which to insert the first element
764 * from the specified collection
765 * @param c collection containing elements to be added to this list
766 * @return {@code true} if this list changed as a result of the call
767 * @throws IndexOutOfBoundsException {@inheritDoc}
768 * @throws NullPointerException if the specified collection is null
769 * @see #add(int,Object)
770 */
771 public boolean addAll(int index, Collection<? extends E> c) {
772 Object[] cs = c.toArray();
773 synchronized (lock) {
774 Object[] elements = getArray();
775 int len = elements.length;
776 if (index > len || index < 0)
777 throw new IndexOutOfBoundsException(outOfBounds(index, len));
778 if (cs.length == 0)
779 return false;
780 int numMoved = len - index;
781 Object[] newElements;
782 if (numMoved == 0)
783 newElements = Arrays.copyOf(elements, len + cs.length);
784 else {
785 newElements = new Object[len + cs.length];
786 System.arraycopy(elements, 0, newElements, 0, index);
787 System.arraycopy(elements, index,
788 newElements, index + cs.length,
789 numMoved);
790 }
791 System.arraycopy(cs, 0, newElements, index, cs.length);
792 setArray(newElements);
793 return true;
794 }
795 }
796
797 /**
798 * @throws NullPointerException {@inheritDoc}
799 */
800 public void forEach(Consumer<? super E> action) {
801 Objects.requireNonNull(action);
802 for (Object x : getArray()) {
803 @SuppressWarnings("unchecked") E e = (E) x;
804 action.accept(e);
805 }
806 }
807
849 }
850 // Did filter reentrantly modify the list?
851 if (es != getArray())
852 throw new ConcurrentModificationException();
853 final Object[] newElts = Arrays.copyOf(es, es.length - deleted);
854 int w = beg;
855 for (i = beg; i < end; i++)
856 if (isClear(deathRow, i - beg))
857 newElts[w++] = es[i];
858 System.arraycopy(es, i, newElts, w, es.length - i);
859 setArray(newElts);
860 return true;
861 } else {
862 if (es != getArray())
863 throw new ConcurrentModificationException();
864 return false;
865 }
866 }
867
868 public void replaceAll(UnaryOperator<E> operator) {
869 Objects.requireNonNull(operator);
870 synchronized (lock) {
871 replaceAll(operator, 0, getArray().length);
872 }
873 }
874
875 void replaceAll(UnaryOperator<E> operator, int i, int end) {
876 // assert Thread.holdsLock(lock);
877 final Object[] es = getArray().clone();
878 for (; i < end; i++)
879 es[i] = operator.apply(elementAt(es, i));
880 setArray(es);
881 }
882
883 public void sort(Comparator<? super E> c) {
884 synchronized (lock) {
885 sort(c, 0, getArray().length);
886 }
887 }
888
889 @SuppressWarnings("unchecked")
890 void sort(Comparator<? super E> c, int i, int end) {
891 // assert Thread.holdsLock(lock);
892 final Object[] es = getArray().clone();
893 Arrays.sort(es, i, end, (Comparator<Object>)c);
894 setArray(es);
895 }
896
897 /**
898 * Saves this list to a stream (that is, serializes it).
899 *
900 * @param s the stream
901 * @throws java.io.IOException if an I/O error occurs
902 * @serialData The length of the array backing the list is emitted
903 * (int), followed by all of its elements (each an Object)
904 * in the proper order.
905 */
906 private void writeObject(java.io.ObjectOutputStream s)
907 throws java.io.IOException {
908
909 s.defaultWriteObject();
910
911 Object[] elements = getArray();
912 // Write out array length
913 s.writeInt(elements.length);
914
915 // Write out all elements in the proper order.
916 for (Object element : elements)
917 s.writeObject(element);
918 }
919
920 /**
921 * Reconstitutes this list from a stream (that is, deserializes it).
922 * @param s the stream
923 * @throws ClassNotFoundException if the class of a serialized object
924 * could not be found
925 * @throws java.io.IOException if an I/O error occurs
926 */
927 private void readObject(java.io.ObjectInputStream s)
928 throws java.io.IOException, ClassNotFoundException {
929
930 s.defaultReadObject();
931
932 // bind to new lock
933 resetLock();
934
935 // Read in array length and allocate array
936 int len = s.readInt();
937 SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, len);
938 Object[] elements = new Object[len];
939
940 // Read in all elements in the proper order.
941 for (int i = 0; i < len; i++)
942 elements[i] = s.readObject();
943 setArray(elements);
944 }
945
946 /**
947 * Returns a string representation of this list. The string
948 * representation consists of the string representations of the list's
949 * elements in the order they are returned by its iterator, enclosed in
950 * square brackets ({@code "[]"}). Adjacent elements are separated by
951 * the characters {@code ", "} (comma and space). Elements are
952 * converted to strings as by {@link String#valueOf(Object)}.
953 *
954 * @return a string representation of this list
955 */
956 public String toString() {
957 return Arrays.toString(getArray());
958 }
959
960 /**
961 * Compares the specified object with this list for equality.
962 * Returns {@code true} if the specified object is the same object
963 * as this object, or if it is also a {@link List} and the sequence
969 * Two elements {@code e1} and {@code e2} are considered
970 * <em>equal</em> if {@code Objects.equals(e1, e2)}.
971 *
972 * @param o the object to be compared for equality with this list
973 * @return {@code true} if the specified object is equal to this list
974 */
975 public boolean equals(Object o) {
976 if (o == this)
977 return true;
978 if (!(o instanceof List))
979 return false;
980
981 List<?> list = (List<?>)o;
982 Iterator<?> it = list.iterator();
983 for (Object element : getArray())
984 if (!it.hasNext() || !Objects.equals(element, it.next()))
985 return false;
986 return !it.hasNext();
987 }
988
989 /**
990 * Returns the hash code value for this list.
991 *
992 * <p>This implementation uses the definition in {@link List#hashCode}.
993 *
994 * @return the hash code value for this list
995 */
996 public int hashCode() {
997 int hashCode = 1;
998 for (Object x : getArray())
999 hashCode = 31 * hashCode + (x == null ? 0 : x.hashCode());
1000 return hashCode;
1001 }
1002
1003 /**
1004 * Returns an iterator over the elements in this list in proper sequence.
1005 *
1006 * <p>The returned iterator provides a snapshot of the state of the list
1007 * when the iterator was constructed. No synchronization is needed while
1008 * traversing the iterator. The iterator does <em>NOT</em> support the
1009 * {@code remove} method.
1010 *
1011 * @return an iterator over the elements in this list in proper sequence
1012 */
1013 public Iterator<E> iterator() {
1014 return new COWIterator<E>(getArray(), 0);
1015 }
1016
1017 /**
1018 * {@inheritDoc}
1019 *
1020 * <p>The returned iterator provides a snapshot of the state of the list
1021 * when the iterator was constructed. No synchronization is needed while
1022 * traversing the iterator. The iterator does <em>NOT</em> support the
1023 * {@code remove}, {@code set} or {@code add} methods.
1024 */
1025 public ListIterator<E> listIterator() {
1026 return new COWIterator<E>(getArray(), 0);
1027 }
1028
1029 /**
1030 * {@inheritDoc}
1031 *
1032 * <p>The returned iterator provides a snapshot of the state of the list
1033 * when the iterator was constructed. No synchronization is needed while
1034 * traversing the iterator. The iterator does <em>NOT</em> support the
1035 * {@code remove}, {@code set} or {@code add} methods.
1036 *
1037 * @throws IndexOutOfBoundsException {@inheritDoc}
1038 */
1039 public ListIterator<E> listIterator(int index) {
1040 Object[] elements = getArray();
1041 int len = elements.length;
1042 if (index < 0 || index > len)
1043 throw new IndexOutOfBoundsException(outOfBounds(index, len));
1044
1045 return new COWIterator<E>(elements, index);
1046 }
1047
1048 /**
1049 * Returns a {@link Spliterator} over the elements in this list.
1050 *
1051 * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
1052 * {@link Spliterator#ORDERED}, {@link Spliterator#SIZED}, and
1053 * {@link Spliterator#SUBSIZED}.
1054 *
1055 * <p>The spliterator provides a snapshot of the state of the list
1056 * when the spliterator was constructed. No synchronization is needed while
1057 * operating on the spliterator.
1058 *
1059 * @return a {@code Spliterator} over the elements in this list
1060 * @since 1.8
1061 */
1062 public Spliterator<E> spliterator() {
1063 return Spliterators.spliterator
1064 (getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED);
1065 }
1066
1067 static final class COWIterator<E> implements ListIterator<E> {
1068 /** Snapshot of the array */
1069 private final Object[] snapshot;
1070 /** Index of element to be returned by subsequent call to next. */
1071 private int cursor;
1072
1073 COWIterator(Object[] elements, int initialCursor) {
1074 cursor = initialCursor;
1075 snapshot = elements;
1076 }
1077
1078 public boolean hasNext() {
1079 return cursor < snapshot.length;
1080 }
1081
1082 public boolean hasPrevious() {
1083 return cursor > 0;
1084 }
1085
1086 @SuppressWarnings("unchecked")
1087 public E next() {
1088 if (! hasNext())
1089 throw new NoSuchElementException();
1090 return (E) snapshot[cursor++];
1091 }
1092
1093 @SuppressWarnings("unchecked")
1094 public E previous() {
1095 if (! hasPrevious())
1096 throw new NoSuchElementException();
1097 return (E) snapshot[--cursor];
1098 }
1099
1100 public int nextIndex() {
1101 return cursor;
1102 }
1103
1104 public int previousIndex() {
1105 return cursor-1;
1106 }
1107
1108 /**
1109 * Not supported. Always throws UnsupportedOperationException.
1110 * @throws UnsupportedOperationException always; {@code remove}
1111 * is not supported by this iterator.
1112 */
1113 public void remove() {
1114 throw new UnsupportedOperationException();
1115 }
1116
1117 /**
1118 * Not supported. Always throws UnsupportedOperationException.
1119 * @throws UnsupportedOperationException always; {@code set}
1120 * is not supported by this iterator.
1121 */
1122 public void set(E e) {
1123 throw new UnsupportedOperationException();
1124 }
1125
1126 /**
1127 * Not supported. Always throws UnsupportedOperationException.
1128 * @throws UnsupportedOperationException always; {@code add}
1129 * is not supported by this iterator.
1130 */
1131 public void add(E e) {
1132 throw new UnsupportedOperationException();
1133 }
1134
1135 @Override
1136 @SuppressWarnings("unchecked")
1137 public void forEachRemaining(Consumer<? super E> action) {
1138 Objects.requireNonNull(action);
1139 final int size = snapshot.length;
1140 for (int i = cursor; i < size; i++) {
1141 action.accept((E) snapshot[i]);
1142 }
1143 cursor = size;
1144 }
1145 }
1146
1147 /**
1148 * Returns a view of the portion of this list between
1149 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1150 * The returned list is backed by this list, so changes in the
1151 * returned list are reflected in this list.
1152 *
1153 * <p>The semantics of the list returned by this method become
1154 * undefined if the backing list (i.e., this list) is modified in
1155 * any way other than via the returned list.
1156 *
1157 * @param fromIndex low endpoint (inclusive) of the subList
1158 * @param toIndex high endpoint (exclusive) of the subList
1159 * @return a view of the specified range within this list
1160 * @throws IndexOutOfBoundsException {@inheritDoc}
1161 */
1162 public List<E> subList(int fromIndex, int toIndex) {
1163 synchronized (lock) {
1164 Object[] elements = getArray();
1165 int len = elements.length;
1166 if (fromIndex < 0 || toIndex > len || fromIndex > toIndex)
1167 throw new IndexOutOfBoundsException();
1168 return new COWSubList<E>(this, fromIndex, toIndex);
1169 }
1170 }
1171
1172 /**
1173 * Sublist for CopyOnWriteArrayList.
1174 */
1175 private static class COWSubList<E>
1176 extends AbstractList<E>
1177 implements RandomAccess
1178 {
1179 private final CopyOnWriteArrayList<E> l;
1180 private final int offset;
1181 private int size;
1182 private Object[] expectedArray;
1183
1184 // only call this holding l's lock
1185 COWSubList(CopyOnWriteArrayList<E> list,
1186 int fromIndex, int toIndex) {
1187 // assert Thread.holdsLock(list.lock);
1188 l = list;
1189 expectedArray = l.getArray();
1190 offset = fromIndex;
1191 size = toIndex - fromIndex;
1192 }
1193
1194 // only call this holding l's lock
1195 private void checkForComodification() {
1196 // assert Thread.holdsLock(l.lock);
1197 if (l.getArray() != expectedArray)
1198 throw new ConcurrentModificationException();
1199 }
1200
1201 private Object[] getArrayChecked() {
1202 // assert Thread.holdsLock(l.lock);
1203 Object[] a = l.getArray();
1204 if (a != expectedArray)
1205 throw new ConcurrentModificationException();
1206 return a;
1207 }
1208
1209 // only call this holding l's lock
1210 private void rangeCheck(int index) {
1211 // assert Thread.holdsLock(l.lock);
1212 if (index < 0 || index >= size)
1213 throw new IndexOutOfBoundsException(outOfBounds(index, size));
1214 }
1215
1216 public E set(int index, E element) {
1217 synchronized (l.lock) {
1218 rangeCheck(index);
1219 checkForComodification();
1220 E x = l.set(offset + index, element);
1221 expectedArray = l.getArray();
1222 return x;
1223 }
1224 }
1225
1226 public E get(int index) {
1227 synchronized (l.lock) {
1228 rangeCheck(index);
1229 checkForComodification();
1230 return l.get(offset + index);
1231 }
1232 }
1233
1234 public int size() {
1235 synchronized (l.lock) {
1236 checkForComodification();
1237 return size;
1238 }
1239 }
1240
1241 public boolean add(E element) {
1242 synchronized (l.lock) {
1243 checkForComodification();
1244 l.add(offset + size, element);
1245 expectedArray = l.getArray();
1246 size++;
1247 }
1248 return true;
1249 }
1250
1251 public void add(int index, E element) {
1252 synchronized (l.lock) {
1253 checkForComodification();
1254 if (index < 0 || index > size)
1255 throw new IndexOutOfBoundsException
1256 (outOfBounds(index, size));
1257 l.add(offset + index, element);
1258 expectedArray = l.getArray();
1259 size++;
1260 }
1261 }
1262
1263 public boolean addAll(Collection<? extends E> c) {
1264 synchronized (l.lock) {
1265 final Object[] oldArray = getArrayChecked();
1266 boolean modified = l.addAll(offset + size, c);
1267 size += (expectedArray = l.getArray()).length - oldArray.length;
1268 return modified;
1269 }
1270 }
1271
1272 public void clear() {
1273 synchronized (l.lock) {
1274 checkForComodification();
1275 l.removeRange(offset, offset + size);
1276 expectedArray = l.getArray();
1277 size = 0;
1278 }
1279 }
1280
1281 public E remove(int index) {
1282 synchronized (l.lock) {
1283 rangeCheck(index);
1284 checkForComodification();
1285 E result = l.remove(offset + index);
1286 expectedArray = l.getArray();
1287 size--;
1288 return result;
1289 }
1290 }
1291
1292 public boolean remove(Object o) {
1293 synchronized (l.lock) {
1294 checkForComodification();
1295 int index = indexOf(o);
1296 if (index == -1)
1297 return false;
1298 remove(index);
1299 return true;
1300 }
1301 }
1302
1303 public Iterator<E> iterator() {
1304 synchronized (l.lock) {
1305 checkForComodification();
1306 return new COWSubListIterator<E>(l, 0, offset, size);
1307 }
1308 }
1309
1310 public ListIterator<E> listIterator(int index) {
1311 synchronized (l.lock) {
1312 checkForComodification();
1313 if (index < 0 || index > size)
1314 throw new IndexOutOfBoundsException
1315 (outOfBounds(index, size));
1316 return new COWSubListIterator<E>(l, index, offset, size);
1317 }
1318 }
1319
1320 public List<E> subList(int fromIndex, int toIndex) {
1321 synchronized (l.lock) {
1322 checkForComodification();
1323 if (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
1324 throw new IndexOutOfBoundsException();
1325 return new COWSubList<E>(l, fromIndex + offset,
1326 toIndex + offset);
1327 }
1328 }
1329
1330 public void forEach(Consumer<? super E> action) {
1331 Objects.requireNonNull(action);
1332 int i, end; final Object[] es;
1333 synchronized (l.lock) {
1334 es = getArrayChecked();
1335 i = offset;
1336 end = i + size;
1337 }
1338 for (; i < end; i++)
1339 action.accept(elementAt(es, i));
1340 }
1341
1342 public void replaceAll(UnaryOperator<E> operator) {
1343 Objects.requireNonNull(operator);
1344 synchronized (l.lock) {
1345 checkForComodification();
1346 l.replaceAll(operator, offset, offset + size);
1347 expectedArray = l.getArray();
1348 }
1349 }
1350
1351 public void sort(Comparator<? super E> c) {
1352 synchronized (l.lock) {
1353 checkForComodification();
1354 l.sort(c, offset, offset + size);
1355 expectedArray = l.getArray();
1356 }
1357 }
1358
1359 public boolean removeAll(Collection<?> c) {
1360 Objects.requireNonNull(c);
1361 return bulkRemove(e -> c.contains(e));
1362 }
1363
1364 public boolean retainAll(Collection<?> c) {
1365 Objects.requireNonNull(c);
1366 return bulkRemove(e -> !c.contains(e));
1367 }
1368
1369 public boolean removeIf(Predicate<? super E> filter) {
1370 Objects.requireNonNull(filter);
1371 return bulkRemove(filter);
1372 }
1373
1374 private boolean bulkRemove(Predicate<? super E> filter) {
1375 synchronized (l.lock) {
1376 final Object[] oldArray = getArrayChecked();
1377 boolean modified = l.bulkRemove(filter, offset, offset + size);
1378 size += (expectedArray = l.getArray()).length - oldArray.length;
1379 return modified;
1380 }
1381 }
1382
1383 public Spliterator<E> spliterator() {
1384 synchronized (l.lock) {
1385 return Spliterators.spliterator(
1386 getArrayChecked(), offset, offset + size,
1387 Spliterator.IMMUTABLE | Spliterator.ORDERED);
1388 }
1389 }
1390
1391 }
1392
1393 private static class COWSubListIterator<E> implements ListIterator<E> {
1394 private final ListIterator<E> it;
1395 private final int offset;
1396 private final int size;
1397
1398 COWSubListIterator(List<E> l, int index, int offset, int size) {
1399 this.offset = offset;
1400 this.size = size;
1401 it = l.listIterator(index+offset);
1402 }
1403
1404 public boolean hasNext() {
1405 return nextIndex() < size;
1406 }
1407
1408 public E next() {
1409 if (hasNext())
1410 return it.next();
1411 else
1412 throw new NoSuchElementException();
1413 }
1414
1415 public boolean hasPrevious() {
1416 return previousIndex() >= 0;
1417 }
1418
1419 public E previous() {
1420 if (hasPrevious())
1421 return it.previous();
1430 public int previousIndex() {
1431 return it.previousIndex() - offset;
1432 }
1433
1434 public void remove() {
1435 throw new UnsupportedOperationException();
1436 }
1437
1438 public void set(E e) {
1439 throw new UnsupportedOperationException();
1440 }
1441
1442 public void add(E e) {
1443 throw new UnsupportedOperationException();
1444 }
1445
1446 @Override
1447 @SuppressWarnings("unchecked")
1448 public void forEachRemaining(Consumer<? super E> action) {
1449 Objects.requireNonNull(action);
1450 while (nextIndex() < size) {
1451 action.accept(it.next());
1452 }
1453 }
1454 }
1455
1456 /** Initializes the lock; for use when deserializing or cloning. */
1457 private void resetLock() {
1458 Field lockField = java.security.AccessController.doPrivileged(
1459 (java.security.PrivilegedAction<Field>) () -> {
1460 try {
1461 Field f = CopyOnWriteArrayList.class
1462 .getDeclaredField("lock");
1463 f.setAccessible(true);
1464 return f;
1465 } catch (ReflectiveOperationException e) {
1466 throw new Error(e);
1467 }});
1468 try {
1469 lockField.set(this, new Object());
1470 } catch (IllegalAccessException e) {
|
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 */
24
25 /*
26 * Written by Doug Lea with assistance from members of JCP JSR-166
27 * Expert Group. Adapted and released, under explicit permission,
28 * from JDK ArrayList.java which carries the following copyright:
29 *
30 * Copyright 1997 by Sun Microsystems, Inc.,
31 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
32 * All rights reserved.
33 */
34
35 package java.util.concurrent;
36
37 import java.lang.reflect.Field;
38 import java.util.Arrays;
39 import java.util.Collection;
40 import java.util.Comparator;
41 import java.util.ConcurrentModificationException;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.ListIterator;
45 import java.util.NoSuchElementException;
46 import java.util.Objects;
47 import java.util.RandomAccess;
48 import java.util.Spliterator;
49 import java.util.Spliterators;
50 import java.util.function.Consumer;
51 import java.util.function.Predicate;
52 import java.util.function.UnaryOperator;
53 import jdk.internal.misc.SharedSecrets;
54
55 /**
56 * A thread-safe variant of {@link java.util.ArrayList} in which all mutative
57 * operations ({@code add}, {@code set}, and so on) are implemented by
116 final void setArray(Object[] a) {
117 array = a;
118 }
119
120 /**
121 * Creates an empty list.
122 */
123 public CopyOnWriteArrayList() {
124 setArray(new Object[0]);
125 }
126
127 /**
128 * Creates a list containing the elements of the specified
129 * collection, in the order they are returned by the collection's
130 * iterator.
131 *
132 * @param c the collection of initially held elements
133 * @throws NullPointerException if the specified collection is null
134 */
135 public CopyOnWriteArrayList(Collection<? extends E> c) {
136 Object[] es;
137 if (c.getClass() == CopyOnWriteArrayList.class)
138 es = ((CopyOnWriteArrayList<?>)c).getArray();
139 else {
140 es = c.toArray();
141 // defend against c.toArray (incorrectly) not returning Object[]
142 // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
143 if (es.getClass() != Object[].class)
144 es = Arrays.copyOf(es, es.length, Object[].class);
145 }
146 setArray(es);
147 }
148
149 /**
150 * Creates a list holding a copy of the given array.
151 *
152 * @param toCopyIn the array (a copy of this array is used as the
153 * internal array)
154 * @throws NullPointerException if the specified array is null
155 */
156 public CopyOnWriteArrayList(E[] toCopyIn) {
157 setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class));
158 }
159
160 /**
161 * Returns the number of elements in this list.
162 *
163 * @return the number of elements in this list
164 */
165 public int size() {
166 return getArray().length;
167 }
168
169 /**
170 * Returns {@code true} if this list contains no elements.
171 *
172 * @return {@code true} if this list contains no elements
173 */
174 public boolean isEmpty() {
175 return size() == 0;
176 }
177
178 /**
179 * static version of indexOf, to allow repeated calls without
180 * needing to re-acquire array each time.
181 * @param o element to search for
182 * @param es the array
183 * @param from first index to search
184 * @param to one past last index to search
185 * @return index of element, or -1 if absent
186 */
187 private static int indexOfRange(Object o, Object[] es, int from, int to) {
188 if (o == null) {
189 for (int i = from; i < to; i++)
190 if (es[i] == null)
191 return i;
192 } else {
193 for (int i = from; i < to; i++)
194 if (o.equals(es[i]))
195 return i;
196 }
197 return -1;
198 }
199
200 /**
201 * static version of lastIndexOf.
202 * @param o element to search for
203 * @param es the array
204 * @param from index of first element of range, last element to search
205 * @param to one past last element of range, first element to search
206 * @return index of element, or -1 if absent
207 */
208 private static int lastIndexOfRange(Object o, Object[] es, int from, int to) {
209 if (o == null) {
210 for (int i = to - 1; i >= from; i--)
211 if (es[i] == null)
212 return i;
213 } else {
214 for (int i = to - 1; i >= from; i--)
215 if (o.equals(es[i]))
216 return i;
217 }
218 return -1;
219 }
220
221 /**
222 * Returns {@code true} if this list contains the specified element.
223 * More formally, returns {@code true} if and only if this list contains
224 * at least one element {@code e} such that {@code Objects.equals(o, e)}.
225 *
226 * @param o element whose presence in this list is to be tested
227 * @return {@code true} if this list contains the specified element
228 */
229 public boolean contains(Object o) {
230 return indexOf(o) >= 0;
231 }
232
233 /**
234 * {@inheritDoc}
235 */
236 public int indexOf(Object o) {
237 Object[] es = getArray();
238 return indexOfRange(o, es, 0, es.length);
239 }
240
241 /**
242 * Returns the index of the first occurrence of the specified element in
243 * this list, searching forwards from {@code index}, or returns -1 if
244 * the element is not found.
245 * More formally, returns the lowest index {@code i} such that
246 * {@code i >= index && Objects.equals(get(i), e)},
247 * or -1 if there is no such index.
248 *
249 * @param e element to search for
250 * @param index index to start searching from
251 * @return the index of the first occurrence of the element in
252 * this list at position {@code index} or later in the list;
253 * {@code -1} if the element is not found.
254 * @throws IndexOutOfBoundsException if the specified index is negative
255 */
256 public int indexOf(E e, int index) {
257 Object[] es = getArray();
258 return indexOfRange(e, es, index, es.length);
259 }
260
261 /**
262 * {@inheritDoc}
263 */
264 public int lastIndexOf(Object o) {
265 Object[] es = getArray();
266 return lastIndexOfRange(o, es, 0, es.length);
267 }
268
269 /**
270 * Returns the index of the last occurrence of the specified element in
271 * this list, searching backwards from {@code index}, or returns -1 if
272 * the element is not found.
273 * More formally, returns the highest index {@code i} such that
274 * {@code i <= index && Objects.equals(get(i), e)},
275 * or -1 if there is no such index.
276 *
277 * @param e element to search for
278 * @param index index to start searching backwards from
279 * @return the index of the last occurrence of the element at position
280 * less than or equal to {@code index} in this list;
281 * -1 if the element is not found.
282 * @throws IndexOutOfBoundsException if the specified index is greater
283 * than or equal to the current size of this list
284 */
285 public int lastIndexOf(E e, int index) {
286 Object[] es = getArray();
287 return lastIndexOfRange(e, es, 0, index + 1);
288 }
289
290 /**
291 * Returns a shallow copy of this list. (The elements themselves
292 * are not copied.)
293 *
294 * @return a clone of this list
295 */
296 public Object clone() {
297 try {
298 @SuppressWarnings("unchecked")
299 CopyOnWriteArrayList<E> clone =
300 (CopyOnWriteArrayList<E>) super.clone();
301 clone.resetLock();
302 return clone;
303 } catch (CloneNotSupportedException e) {
304 // this shouldn't happen, since we are Cloneable
305 throw new InternalError();
306 }
307 }
308
309 /**
310 * Returns an array containing all of the elements in this list
311 * in proper sequence (from first to last element).
312 *
313 * <p>The returned array will be "safe" in that no references to it are
314 * maintained by this list. (In other words, this method must allocate
315 * a new array). The caller is thus free to modify the returned array.
316 *
317 * <p>This method acts as bridge between array-based and collection-based
318 * APIs.
319 *
320 * @return an array containing all the elements in this list
321 */
322 public Object[] toArray() {
323 return getArray().clone();
324 }
325
326 /**
327 * Returns an array containing all of the elements in this list in
328 * proper sequence (from first to last element); the runtime type of
329 * the returned array is that of the specified array. If the list fits
330 * in the specified array, it is returned therein. Otherwise, a new
331 * array is allocated with the runtime type of the specified array and
332 * the size of this list.
333 *
334 * <p>If this list fits in the specified array with room to spare
335 * (i.e., the array has more elements than this list), the element in
336 * the array immediately following the end of the list is set to
337 * {@code null}. (This is useful in determining the length of this
338 * list <i>only</i> if the caller knows that this list does not contain
339 * any null elements.)
340 *
341 * <p>Like the {@link #toArray()} method, this method acts as bridge between
342 * array-based and collection-based APIs. Further, this method allows
343 * precise control over the runtime type of the output array, and may,
346 * <p>Suppose {@code x} is a list known to contain only strings.
347 * The following code can be used to dump the list into a newly
348 * allocated array of {@code String}:
349 *
350 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
351 *
352 * Note that {@code toArray(new Object[0])} is identical in function to
353 * {@code toArray()}.
354 *
355 * @param a the array into which the elements of the list are to
356 * be stored, if it is big enough; otherwise, a new array of the
357 * same runtime type is allocated for this purpose.
358 * @return an array containing all the elements in this list
359 * @throws ArrayStoreException if the runtime type of the specified array
360 * is not a supertype of the runtime type of every element in
361 * this list
362 * @throws NullPointerException if the specified array is null
363 */
364 @SuppressWarnings("unchecked")
365 public <T> T[] toArray(T[] a) {
366 Object[] es = getArray();
367 int len = es.length;
368 if (a.length < len)
369 return (T[]) Arrays.copyOf(es, len, a.getClass());
370 else {
371 System.arraycopy(es, 0, a, 0, len);
372 if (a.length > len)
373 a[len] = null;
374 return a;
375 }
376 }
377
378 // Positional Access Operations
379
380 @SuppressWarnings("unchecked")
381 static <E> E elementAt(Object[] a, int index) {
382 return (E) a[index];
383 }
384
385 static String outOfBounds(int index, int size) {
386 return "Index: " + index + ", Size: " + size;
387 }
388
389 /**
390 * {@inheritDoc}
391 *
392 * @throws IndexOutOfBoundsException {@inheritDoc}
393 */
394 public E get(int index) {
395 return elementAt(getArray(), index);
396 }
397
398 /**
399 * Replaces the element at the specified position in this list with the
400 * specified element.
401 *
402 * @throws IndexOutOfBoundsException {@inheritDoc}
403 */
404 public E set(int index, E element) {
405 synchronized (lock) {
406 Object[] es = getArray();
407 E oldValue = elementAt(es, index);
408
409 if (oldValue != element) {
410 es = es.clone();
411 es[index] = element;
412 setArray(es);
413 }
414 return oldValue;
415 }
416 }
417
418 /**
419 * Appends the specified element to the end of this list.
420 *
421 * @param e element to be appended to this list
422 * @return {@code true} (as specified by {@link Collection#add})
423 */
424 public boolean add(E e) {
425 synchronized (lock) {
426 Object[] es = getArray();
427 int len = es.length;
428 es = Arrays.copyOf(es, len + 1);
429 es[len] = e;
430 setArray(es);
431 return true;
432 }
433 }
434
435 /**
436 * Inserts the specified element at the specified position in this
437 * list. Shifts the element currently at that position (if any) and
438 * any subsequent elements to the right (adds one to their indices).
439 *
440 * @throws IndexOutOfBoundsException {@inheritDoc}
441 */
442 public void add(int index, E element) {
443 synchronized (lock) {
444 Object[] es = getArray();
445 int len = es.length;
446 if (index > len || index < 0)
447 throw new IndexOutOfBoundsException(outOfBounds(index, len));
448 Object[] newElements;
449 int numMoved = len - index;
450 if (numMoved == 0)
451 newElements = Arrays.copyOf(es, len + 1);
452 else {
453 newElements = new Object[len + 1];
454 System.arraycopy(es, 0, newElements, 0, index);
455 System.arraycopy(es, index, newElements, index + 1,
456 numMoved);
457 }
458 newElements[index] = element;
459 setArray(newElements);
460 }
461 }
462
463 /**
464 * Removes the element at the specified position in this list.
465 * Shifts any subsequent elements to the left (subtracts one from their
466 * indices). Returns the element that was removed from the list.
467 *
468 * @throws IndexOutOfBoundsException {@inheritDoc}
469 */
470 public E remove(int index) {
471 synchronized (lock) {
472 Object[] es = getArray();
473 int len = es.length;
474 E oldValue = elementAt(es, index);
475 int numMoved = len - index - 1;
476 Object[] newElements;
477 if (numMoved == 0)
478 newElements = Arrays.copyOf(es, len - 1);
479 else {
480 newElements = new Object[len - 1];
481 System.arraycopy(es, 0, newElements, 0, index);
482 System.arraycopy(es, index + 1, newElements, index,
483 numMoved);
484 }
485 setArray(newElements);
486 return oldValue;
487 }
488 }
489
490 /**
491 * Removes the first occurrence of the specified element from this list,
492 * if it is present. If this list does not contain the element, it is
493 * unchanged. More formally, removes the element with the lowest index
494 * {@code i} such that {@code Objects.equals(o, get(i))}
495 * (if such an element exists). Returns {@code true} if this list
496 * contained the specified element (or equivalently, if this list
497 * changed as a result of the call).
498 *
499 * @param o element to be removed from this list, if present
500 * @return {@code true} if this list contained the specified element
501 */
502 public boolean remove(Object o) {
503 Object[] snapshot = getArray();
504 int index = indexOfRange(o, snapshot, 0, snapshot.length);
505 return index >= 0 && remove(o, snapshot, index);
506 }
507
508 /**
509 * A version of remove(Object) using the strong hint that given
510 * recent snapshot contains o at the given index.
511 */
512 private boolean remove(Object o, Object[] snapshot, int index) {
513 synchronized (lock) {
514 Object[] current = getArray();
515 int len = current.length;
516 if (snapshot != current) findIndex: {
517 int prefix = Math.min(index, len);
518 for (int i = 0; i < prefix; i++) {
519 if (current[i] != snapshot[i]
520 && Objects.equals(o, current[i])) {
521 index = i;
522 break findIndex;
523 }
524 }
525 if (index >= len)
526 return false;
527 if (current[index] == o)
528 break findIndex;
529 index = indexOfRange(o, current, index, len);
530 if (index < 0)
531 return false;
532 }
533 Object[] newElements = new Object[len - 1];
534 System.arraycopy(current, 0, newElements, 0, index);
535 System.arraycopy(current, index + 1,
536 newElements, index,
537 len - index - 1);
538 setArray(newElements);
539 return true;
540 }
541 }
542
543 /**
544 * Removes from this list all of the elements whose index is between
545 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
546 * Shifts any succeeding elements to the left (reduces their index).
547 * This call shortens the list by {@code (toIndex - fromIndex)} elements.
548 * (If {@code toIndex==fromIndex}, this operation has no effect.)
549 *
550 * @param fromIndex index of first element to be removed
551 * @param toIndex index after last element to be removed
552 * @throws IndexOutOfBoundsException if fromIndex or toIndex out of range
553 * ({@code fromIndex < 0 || toIndex > size() || toIndex < fromIndex})
554 */
555 void removeRange(int fromIndex, int toIndex) {
556 synchronized (lock) {
557 Object[] es = getArray();
558 int len = es.length;
559
560 if (fromIndex < 0 || toIndex > len || toIndex < fromIndex)
561 throw new IndexOutOfBoundsException();
562 int newlen = len - (toIndex - fromIndex);
563 int numMoved = len - toIndex;
564 if (numMoved == 0)
565 setArray(Arrays.copyOf(es, newlen));
566 else {
567 Object[] newElements = new Object[newlen];
568 System.arraycopy(es, 0, newElements, 0, fromIndex);
569 System.arraycopy(es, toIndex, newElements,
570 fromIndex, numMoved);
571 setArray(newElements);
572 }
573 }
574 }
575
576 /**
577 * Appends the element, if not present.
578 *
579 * @param e element to be added to this list, if absent
580 * @return {@code true} if the element was added
581 */
582 public boolean addIfAbsent(E e) {
583 Object[] snapshot = getArray();
584 return indexOfRange(e, snapshot, 0, snapshot.length) < 0
585 && addIfAbsent(e, snapshot);
586 }
587
588 /**
589 * A version of addIfAbsent using the strong hint that given
590 * recent snapshot does not contain e.
591 */
592 private boolean addIfAbsent(E e, Object[] snapshot) {
593 synchronized (lock) {
594 Object[] current = getArray();
595 int len = current.length;
596 if (snapshot != current) {
597 // Optimize for lost race to another addXXX operation
598 int common = Math.min(snapshot.length, len);
599 for (int i = 0; i < common; i++)
600 if (current[i] != snapshot[i]
601 && Objects.equals(e, current[i]))
602 return false;
603 if (indexOfRange(e, current, common, len) >= 0)
604 return false;
605 }
606 Object[] newElements = Arrays.copyOf(current, len + 1);
607 newElements[len] = e;
608 setArray(newElements);
609 return true;
610 }
611 }
612
613 /**
614 * Returns {@code true} if this list contains all of the elements of the
615 * specified collection.
616 *
617 * @param c collection to be checked for containment in this list
618 * @return {@code true} if this list contains all of the elements of the
619 * specified collection
620 * @throws NullPointerException if the specified collection is null
621 * @see #contains(Object)
622 */
623 public boolean containsAll(Collection<?> c) {
624 Object[] es = getArray();
625 int len = es.length;
626 for (Object e : c) {
627 if (indexOfRange(e, es, 0, len) < 0)
628 return false;
629 }
630 return true;
631 }
632
633 /**
634 * Removes from this list all of its elements that are contained in
635 * the specified collection. This is a particularly expensive operation
636 * in this class because of the need for an internal temporary array.
637 *
638 * @param c collection containing elements to be removed from this list
639 * @return {@code true} if this list changed as a result of the call
640 * @throws ClassCastException if the class of an element of this list
641 * is incompatible with the specified collection
642 * (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>)
643 * @throws NullPointerException if this list contains a null element and the
644 * specified collection does not permit null elements
645 * (<a href="{@docRoot}/java.base/java/util/Collection.html#optional-restrictions">optional</a>),
646 * or if the specified collection is null
647 * @see #remove(Object)
671 Objects.requireNonNull(c);
672 return bulkRemove(e -> !c.contains(e));
673 }
674
675 /**
676 * Appends all of the elements in the specified collection that
677 * are not already contained in this list, to the end of
678 * this list, in the order that they are returned by the
679 * specified collection's iterator.
680 *
681 * @param c collection containing elements to be added to this list
682 * @return the number of elements added
683 * @throws NullPointerException if the specified collection is null
684 * @see #addIfAbsent(Object)
685 */
686 public int addAllAbsent(Collection<? extends E> c) {
687 Object[] cs = c.toArray();
688 if (cs.length == 0)
689 return 0;
690 synchronized (lock) {
691 Object[] es = getArray();
692 int len = es.length;
693 int added = 0;
694 // uniquify and compact elements in cs
695 for (int i = 0; i < cs.length; ++i) {
696 Object e = cs[i];
697 if (indexOfRange(e, es, 0, len) < 0 &&
698 indexOfRange(e, cs, 0, added) < 0)
699 cs[added++] = e;
700 }
701 if (added > 0) {
702 Object[] newElements = Arrays.copyOf(es, len + added);
703 System.arraycopy(cs, 0, newElements, len, added);
704 setArray(newElements);
705 }
706 return added;
707 }
708 }
709
710 /**
711 * Removes all of the elements from this list.
712 * The list will be empty after this call returns.
713 */
714 public void clear() {
715 synchronized (lock) {
716 setArray(new Object[0]);
717 }
718 }
719
720 /**
721 * Appends all of the elements in the specified collection to the end
722 * of this list, in the order that they are returned by the specified
723 * collection's iterator.
724 *
725 * @param c collection containing elements to be added to this list
726 * @return {@code true} if this list changed as a result of the call
727 * @throws NullPointerException if the specified collection is null
728 * @see #add(Object)
729 */
730 public boolean addAll(Collection<? extends E> c) {
731 Object[] cs = (c.getClass() == CopyOnWriteArrayList.class) ?
732 ((CopyOnWriteArrayList<?>)c).getArray() : c.toArray();
733 if (cs.length == 0)
734 return false;
735 synchronized (lock) {
736 Object[] es = getArray();
737 int len = es.length;
738 Object[] newElements;
739 if (len == 0 && cs.getClass() == Object[].class)
740 newElements = cs;
741 else {
742 newElements = Arrays.copyOf(es, len + cs.length);
743 System.arraycopy(cs, 0, newElements, len, cs.length);
744 }
745 setArray(newElements);
746 return true;
747 }
748 }
749
750 /**
751 * Inserts all of the elements in the specified collection into this
752 * list, starting at the specified position. Shifts the element
753 * currently at that position (if any) and any subsequent elements to
754 * the right (increases their indices). The new elements will appear
755 * in this list in the order that they are returned by the
756 * specified collection's iterator.
757 *
758 * @param index index at which to insert the first element
759 * from the specified collection
760 * @param c collection containing elements to be added to this list
761 * @return {@code true} if this list changed as a result of the call
762 * @throws IndexOutOfBoundsException {@inheritDoc}
763 * @throws NullPointerException if the specified collection is null
764 * @see #add(int,Object)
765 */
766 public boolean addAll(int index, Collection<? extends E> c) {
767 Object[] cs = c.toArray();
768 synchronized (lock) {
769 Object[] es = getArray();
770 int len = es.length;
771 if (index > len || index < 0)
772 throw new IndexOutOfBoundsException(outOfBounds(index, len));
773 if (cs.length == 0)
774 return false;
775 int numMoved = len - index;
776 Object[] newElements;
777 if (numMoved == 0)
778 newElements = Arrays.copyOf(es, len + cs.length);
779 else {
780 newElements = new Object[len + cs.length];
781 System.arraycopy(es, 0, newElements, 0, index);
782 System.arraycopy(es, index,
783 newElements, index + cs.length,
784 numMoved);
785 }
786 System.arraycopy(cs, 0, newElements, index, cs.length);
787 setArray(newElements);
788 return true;
789 }
790 }
791
792 /**
793 * @throws NullPointerException {@inheritDoc}
794 */
795 public void forEach(Consumer<? super E> action) {
796 Objects.requireNonNull(action);
797 for (Object x : getArray()) {
798 @SuppressWarnings("unchecked") E e = (E) x;
799 action.accept(e);
800 }
801 }
802
844 }
845 // Did filter reentrantly modify the list?
846 if (es != getArray())
847 throw new ConcurrentModificationException();
848 final Object[] newElts = Arrays.copyOf(es, es.length - deleted);
849 int w = beg;
850 for (i = beg; i < end; i++)
851 if (isClear(deathRow, i - beg))
852 newElts[w++] = es[i];
853 System.arraycopy(es, i, newElts, w, es.length - i);
854 setArray(newElts);
855 return true;
856 } else {
857 if (es != getArray())
858 throw new ConcurrentModificationException();
859 return false;
860 }
861 }
862
863 public void replaceAll(UnaryOperator<E> operator) {
864 synchronized (lock) {
865 replaceAllRange(operator, 0, getArray().length);
866 }
867 }
868
869 void replaceAllRange(UnaryOperator<E> operator, int i, int end) {
870 // assert Thread.holdsLock(lock);
871 Objects.requireNonNull(operator);
872 final Object[] es = getArray().clone();
873 for (; i < end; i++)
874 es[i] = operator.apply(elementAt(es, i));
875 setArray(es);
876 }
877
878 public void sort(Comparator<? super E> c) {
879 synchronized (lock) {
880 sortRange(c, 0, getArray().length);
881 }
882 }
883
884 @SuppressWarnings("unchecked")
885 void sortRange(Comparator<? super E> c, int i, int end) {
886 // assert Thread.holdsLock(lock);
887 final Object[] es = getArray().clone();
888 Arrays.sort(es, i, end, (Comparator<Object>)c);
889 setArray(es);
890 }
891
892 /**
893 * Saves this list to a stream (that is, serializes it).
894 *
895 * @param s the stream
896 * @throws java.io.IOException if an I/O error occurs
897 * @serialData The length of the array backing the list is emitted
898 * (int), followed by all of its elements (each an Object)
899 * in the proper order.
900 */
901 private void writeObject(java.io.ObjectOutputStream s)
902 throws java.io.IOException {
903
904 s.defaultWriteObject();
905
906 Object[] es = getArray();
907 // Write out array length
908 s.writeInt(es.length);
909
910 // Write out all elements in the proper order.
911 for (Object element : es)
912 s.writeObject(element);
913 }
914
915 /**
916 * Reconstitutes this list from a stream (that is, deserializes it).
917 * @param s the stream
918 * @throws ClassNotFoundException if the class of a serialized object
919 * could not be found
920 * @throws java.io.IOException if an I/O error occurs
921 */
922 private void readObject(java.io.ObjectInputStream s)
923 throws java.io.IOException, ClassNotFoundException {
924
925 s.defaultReadObject();
926
927 // bind to new lock
928 resetLock();
929
930 // Read in array length and allocate array
931 int len = s.readInt();
932 SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, len);
933 Object[] es = new Object[len];
934
935 // Read in all elements in the proper order.
936 for (int i = 0; i < len; i++)
937 es[i] = s.readObject();
938 setArray(es);
939 }
940
941 /**
942 * Returns a string representation of this list. The string
943 * representation consists of the string representations of the list's
944 * elements in the order they are returned by its iterator, enclosed in
945 * square brackets ({@code "[]"}). Adjacent elements are separated by
946 * the characters {@code ", "} (comma and space). Elements are
947 * converted to strings as by {@link String#valueOf(Object)}.
948 *
949 * @return a string representation of this list
950 */
951 public String toString() {
952 return Arrays.toString(getArray());
953 }
954
955 /**
956 * Compares the specified object with this list for equality.
957 * Returns {@code true} if the specified object is the same object
958 * as this object, or if it is also a {@link List} and the sequence
964 * Two elements {@code e1} and {@code e2} are considered
965 * <em>equal</em> if {@code Objects.equals(e1, e2)}.
966 *
967 * @param o the object to be compared for equality with this list
968 * @return {@code true} if the specified object is equal to this list
969 */
970 public boolean equals(Object o) {
971 if (o == this)
972 return true;
973 if (!(o instanceof List))
974 return false;
975
976 List<?> list = (List<?>)o;
977 Iterator<?> it = list.iterator();
978 for (Object element : getArray())
979 if (!it.hasNext() || !Objects.equals(element, it.next()))
980 return false;
981 return !it.hasNext();
982 }
983
984 private static int hashCodeOfRange(Object[] es, int from, int to) {
985 int hashCode = 1;
986 for (int i = from; i < to; i++) {
987 Object x = es[i];
988 hashCode = 31 * hashCode + (x == null ? 0 : x.hashCode());
989 }
990 return hashCode;
991 }
992
993 /**
994 * Returns the hash code value for this list.
995 *
996 * <p>This implementation uses the definition in {@link List#hashCode}.
997 *
998 * @return the hash code value for this list
999 */
1000 public int hashCode() {
1001 Object[] es = getArray();
1002 return hashCodeOfRange(es, 0, es.length);
1003 }
1004
1005 /**
1006 * Returns an iterator over the elements in this list in proper sequence.
1007 *
1008 * <p>The returned iterator provides a snapshot of the state of the list
1009 * when the iterator was constructed. No synchronization is needed while
1010 * traversing the iterator. The iterator does <em>NOT</em> support the
1011 * {@code remove} method.
1012 *
1013 * @return an iterator over the elements in this list in proper sequence
1014 */
1015 public Iterator<E> iterator() {
1016 return new COWIterator<E>(getArray(), 0);
1017 }
1018
1019 /**
1020 * {@inheritDoc}
1021 *
1022 * <p>The returned iterator provides a snapshot of the state of the list
1023 * when the iterator was constructed. No synchronization is needed while
1024 * traversing the iterator. The iterator does <em>NOT</em> support the
1025 * {@code remove}, {@code set} or {@code add} methods.
1026 */
1027 public ListIterator<E> listIterator() {
1028 return new COWIterator<E>(getArray(), 0);
1029 }
1030
1031 /**
1032 * {@inheritDoc}
1033 *
1034 * <p>The returned iterator provides a snapshot of the state of the list
1035 * when the iterator was constructed. No synchronization is needed while
1036 * traversing the iterator. The iterator does <em>NOT</em> support the
1037 * {@code remove}, {@code set} or {@code add} methods.
1038 *
1039 * @throws IndexOutOfBoundsException {@inheritDoc}
1040 */
1041 public ListIterator<E> listIterator(int index) {
1042 Object[] es = getArray();
1043 int len = es.length;
1044 if (index < 0 || index > len)
1045 throw new IndexOutOfBoundsException(outOfBounds(index, len));
1046
1047 return new COWIterator<E>(es, index);
1048 }
1049
1050 /**
1051 * Returns a {@link Spliterator} over the elements in this list.
1052 *
1053 * <p>The {@code Spliterator} reports {@link Spliterator#IMMUTABLE},
1054 * {@link Spliterator#ORDERED}, {@link Spliterator#SIZED}, and
1055 * {@link Spliterator#SUBSIZED}.
1056 *
1057 * <p>The spliterator provides a snapshot of the state of the list
1058 * when the spliterator was constructed. No synchronization is needed while
1059 * operating on the spliterator.
1060 *
1061 * @return a {@code Spliterator} over the elements in this list
1062 * @since 1.8
1063 */
1064 public Spliterator<E> spliterator() {
1065 return Spliterators.spliterator
1066 (getArray(), Spliterator.IMMUTABLE | Spliterator.ORDERED);
1067 }
1068
1069 static final class COWIterator<E> implements ListIterator<E> {
1070 /** Snapshot of the array */
1071 private final Object[] snapshot;
1072 /** Index of element to be returned by subsequent call to next. */
1073 private int cursor;
1074
1075 COWIterator(Object[] es, int initialCursor) {
1076 cursor = initialCursor;
1077 snapshot = es;
1078 }
1079
1080 public boolean hasNext() {
1081 return cursor < snapshot.length;
1082 }
1083
1084 public boolean hasPrevious() {
1085 return cursor > 0;
1086 }
1087
1088 @SuppressWarnings("unchecked")
1089 public E next() {
1090 if (! hasNext())
1091 throw new NoSuchElementException();
1092 return (E) snapshot[cursor++];
1093 }
1094
1095 @SuppressWarnings("unchecked")
1096 public E previous() {
1097 if (! hasPrevious())
1098 throw new NoSuchElementException();
1099 return (E) snapshot[--cursor];
1100 }
1101
1102 public int nextIndex() {
1103 return cursor;
1104 }
1105
1106 public int previousIndex() {
1107 return cursor - 1;
1108 }
1109
1110 /**
1111 * Not supported. Always throws UnsupportedOperationException.
1112 * @throws UnsupportedOperationException always; {@code remove}
1113 * is not supported by this iterator.
1114 */
1115 public void remove() {
1116 throw new UnsupportedOperationException();
1117 }
1118
1119 /**
1120 * Not supported. Always throws UnsupportedOperationException.
1121 * @throws UnsupportedOperationException always; {@code set}
1122 * is not supported by this iterator.
1123 */
1124 public void set(E e) {
1125 throw new UnsupportedOperationException();
1126 }
1127
1128 /**
1129 * Not supported. Always throws UnsupportedOperationException.
1130 * @throws UnsupportedOperationException always; {@code add}
1131 * is not supported by this iterator.
1132 */
1133 public void add(E e) {
1134 throw new UnsupportedOperationException();
1135 }
1136
1137 @Override
1138 public void forEachRemaining(Consumer<? super E> action) {
1139 Objects.requireNonNull(action);
1140 final int size = snapshot.length;
1141 int i = cursor;
1142 cursor = size;
1143 for (; i < size; i++)
1144 action.accept(elementAt(snapshot, i));
1145 }
1146 }
1147
1148 /**
1149 * Returns a view of the portion of this list between
1150 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
1151 * The returned list is backed by this list, so changes in the
1152 * returned list are reflected in this list.
1153 *
1154 * <p>The semantics of the list returned by this method become
1155 * undefined if the backing list (i.e., this list) is modified in
1156 * any way other than via the returned list.
1157 *
1158 * @param fromIndex low endpoint (inclusive) of the subList
1159 * @param toIndex high endpoint (exclusive) of the subList
1160 * @return a view of the specified range within this list
1161 * @throws IndexOutOfBoundsException {@inheritDoc}
1162 */
1163 public List<E> subList(int fromIndex, int toIndex) {
1164 synchronized (lock) {
1165 Object[] es = getArray();
1166 int len = es.length;
1167 int size = toIndex - fromIndex;
1168 if (fromIndex < 0 || toIndex > len || size < 0)
1169 throw new IndexOutOfBoundsException();
1170 return new COWSubList(es, fromIndex, size);
1171 }
1172 }
1173
1174 /**
1175 * Sublist for CopyOnWriteArrayList.
1176 */
1177 private class COWSubList implements List<E>, RandomAccess {
1178 private final int offset;
1179 private int size;
1180 private Object[] expectedArray;
1181
1182 COWSubList(Object[] es, int offset, int size) {
1183 // assert Thread.holdsLock(lock);
1184 expectedArray = es;
1185 this.offset = offset;
1186 this.size = size;
1187 }
1188
1189 private void checkForComodification() {
1190 // assert Thread.holdsLock(lock);
1191 if (getArray() != expectedArray)
1192 throw new ConcurrentModificationException();
1193 }
1194
1195 private Object[] getArrayChecked() {
1196 // assert Thread.holdsLock(lock);
1197 Object[] a = getArray();
1198 if (a != expectedArray)
1199 throw new ConcurrentModificationException();
1200 return a;
1201 }
1202
1203 private void rangeCheck(int index) {
1204 // assert Thread.holdsLock(lock);
1205 if (index < 0 || index >= size)
1206 throw new IndexOutOfBoundsException(outOfBounds(index, size));
1207 }
1208
1209 private void rangeCheckForAdd(int index) {
1210 // assert Thread.holdsLock(lock);
1211 if (index < 0 || index > size)
1212 throw new IndexOutOfBoundsException(outOfBounds(index, size));
1213 }
1214
1215 public Object[] toArray() {
1216 final Object[] es;
1217 final int offset;
1218 final int size;
1219 synchronized (lock) {
1220 es = getArrayChecked();
1221 offset = this.offset;
1222 size = this.size;
1223 }
1224 return Arrays.copyOfRange(es, offset, offset + size);
1225 }
1226
1227 @SuppressWarnings("unchecked")
1228 public <T> T[] toArray(T[] a) {
1229 final Object[] es;
1230 final int offset;
1231 final int size;
1232 synchronized (lock) {
1233 es = getArrayChecked();
1234 offset = this.offset;
1235 size = this.size;
1236 }
1237 if (a.length < size)
1238 return (T[]) Arrays.copyOfRange(
1239 es, offset, offset + size, a.getClass());
1240 else {
1241 System.arraycopy(es, offset, a, 0, size);
1242 if (a.length > size)
1243 a[size] = null;
1244 return a;
1245 }
1246 }
1247
1248 public int indexOf(Object o) {
1249 final Object[] es;
1250 final int offset;
1251 final int size;
1252 synchronized (lock) {
1253 es = getArrayChecked();
1254 offset = this.offset;
1255 size = this.size;
1256 }
1257 int i = indexOfRange(o, es, offset, offset + size);
1258 return (i == -1) ? -1 : i - offset;
1259 }
1260
1261 public int lastIndexOf(Object o) {
1262 final Object[] es;
1263 final int offset;
1264 final int size;
1265 synchronized (lock) {
1266 es = getArrayChecked();
1267 offset = this.offset;
1268 size = this.size;
1269 }
1270 int i = lastIndexOfRange(o, es, offset, offset + size);
1271 return (i == -1) ? -1 : i - offset;
1272 }
1273
1274 public boolean contains(Object o) {
1275 return indexOf(o) >= 0;
1276 }
1277
1278 public boolean containsAll(Collection<?> c) {
1279 final Object[] es;
1280 final int offset;
1281 final int size;
1282 synchronized (lock) {
1283 es = getArrayChecked();
1284 offset = this.offset;
1285 size = this.size;
1286 }
1287 for (Object o : c)
1288 if (indexOfRange(o, es, offset, offset + size) < 0)
1289 return false;
1290 return true;
1291 }
1292
1293 public boolean isEmpty() {
1294 return size() == 0;
1295 }
1296
1297 public String toString() {
1298 return Arrays.toString(toArray());
1299 }
1300
1301 public int hashCode() {
1302 final Object[] es;
1303 final int offset;
1304 final int size;
1305 synchronized (lock) {
1306 es = getArrayChecked();
1307 offset = this.offset;
1308 size = this.size;
1309 }
1310 return hashCodeOfRange(es, offset, offset + size);
1311 }
1312
1313 public boolean equals(Object o) {
1314 if (o == this)
1315 return true;
1316 if (!(o instanceof List))
1317 return false;
1318 Iterator<?> it = ((List<?>)o).iterator();
1319
1320 final Object[] es;
1321 final int offset;
1322 final int size;
1323 synchronized (lock) {
1324 es = getArrayChecked();
1325 offset = this.offset;
1326 size = this.size;
1327 }
1328
1329 for (int i = offset, end = offset + size; i < end; i++)
1330 if (!it.hasNext() || !Objects.equals(es[i], it.next()))
1331 return false;
1332 return !it.hasNext();
1333 }
1334
1335 public E set(int index, E element) {
1336 synchronized (lock) {
1337 rangeCheck(index);
1338 checkForComodification();
1339 E x = CopyOnWriteArrayList.this.set(offset + index, element);
1340 expectedArray = getArray();
1341 return x;
1342 }
1343 }
1344
1345 public E get(int index) {
1346 synchronized (lock) {
1347 rangeCheck(index);
1348 checkForComodification();
1349 return CopyOnWriteArrayList.this.get(offset + index);
1350 }
1351 }
1352
1353 public int size() {
1354 synchronized (lock) {
1355 checkForComodification();
1356 return size;
1357 }
1358 }
1359
1360 public boolean add(E element) {
1361 synchronized (lock) {
1362 checkForComodification();
1363 CopyOnWriteArrayList.this.add(offset + size, element);
1364 expectedArray = getArray();
1365 size++;
1366 }
1367 return true;
1368 }
1369
1370 public void add(int index, E element) {
1371 synchronized (lock) {
1372 checkForComodification();
1373 rangeCheckForAdd(index);
1374 CopyOnWriteArrayList.this.add(offset + index, element);
1375 expectedArray = getArray();
1376 size++;
1377 }
1378 }
1379
1380 public boolean addAll(Collection<? extends E> c) {
1381 synchronized (lock) {
1382 final Object[] oldArray = getArrayChecked();
1383 boolean modified =
1384 CopyOnWriteArrayList.this.addAll(offset + size, c);
1385 size += (expectedArray = getArray()).length - oldArray.length;
1386 return modified;
1387 }
1388 }
1389
1390 public boolean addAll(int index, Collection<? extends E> c) {
1391 synchronized (lock) {
1392 rangeCheckForAdd(index);
1393 final Object[] oldArray = getArrayChecked();
1394 boolean modified =
1395 CopyOnWriteArrayList.this.addAll(offset + index, c);
1396 size += (expectedArray = getArray()).length - oldArray.length;
1397 return modified;
1398 }
1399 }
1400
1401 public void clear() {
1402 synchronized (lock) {
1403 checkForComodification();
1404 removeRange(offset, offset + size);
1405 expectedArray = getArray();
1406 size = 0;
1407 }
1408 }
1409
1410 public E remove(int index) {
1411 synchronized (lock) {
1412 rangeCheck(index);
1413 checkForComodification();
1414 E result = CopyOnWriteArrayList.this.remove(offset + index);
1415 expectedArray = getArray();
1416 size--;
1417 return result;
1418 }
1419 }
1420
1421 public boolean remove(Object o) {
1422 synchronized (lock) {
1423 checkForComodification();
1424 int index = indexOf(o);
1425 if (index == -1)
1426 return false;
1427 remove(index);
1428 return true;
1429 }
1430 }
1431
1432 public Iterator<E> iterator() {
1433 return listIterator(0);
1434 }
1435
1436 public ListIterator<E> listIterator() {
1437 return listIterator(0);
1438 }
1439
1440 public ListIterator<E> listIterator(int index) {
1441 synchronized (lock) {
1442 checkForComodification();
1443 rangeCheckForAdd(index);
1444 return new COWSubListIterator<E>(
1445 CopyOnWriteArrayList.this, index, offset, size);
1446 }
1447 }
1448
1449 public List<E> subList(int fromIndex, int toIndex) {
1450 synchronized (lock) {
1451 checkForComodification();
1452 if (fromIndex < 0 || toIndex > size || fromIndex > toIndex)
1453 throw new IndexOutOfBoundsException();
1454 return new COWSubList(expectedArray, fromIndex + offset, toIndex - fromIndex);
1455 }
1456 }
1457
1458 public void forEach(Consumer<? super E> action) {
1459 Objects.requireNonNull(action);
1460 int i, end; final Object[] es;
1461 synchronized (lock) {
1462 es = getArrayChecked();
1463 i = offset;
1464 end = i + size;
1465 }
1466 for (; i < end; i++)
1467 action.accept(elementAt(es, i));
1468 }
1469
1470 public void replaceAll(UnaryOperator<E> operator) {
1471 synchronized (lock) {
1472 checkForComodification();
1473 replaceAllRange(operator, offset, offset + size);
1474 expectedArray = getArray();
1475 }
1476 }
1477
1478 public void sort(Comparator<? super E> c) {
1479 synchronized (lock) {
1480 checkForComodification();
1481 sortRange(c, offset, offset + size);
1482 expectedArray = getArray();
1483 }
1484 }
1485
1486 public boolean removeAll(Collection<?> c) {
1487 Objects.requireNonNull(c);
1488 return bulkRemove(e -> c.contains(e));
1489 }
1490
1491 public boolean retainAll(Collection<?> c) {
1492 Objects.requireNonNull(c);
1493 return bulkRemove(e -> !c.contains(e));
1494 }
1495
1496 public boolean removeIf(Predicate<? super E> filter) {
1497 Objects.requireNonNull(filter);
1498 return bulkRemove(filter);
1499 }
1500
1501 private boolean bulkRemove(Predicate<? super E> filter) {
1502 synchronized (lock) {
1503 final Object[] oldArray = getArrayChecked();
1504 boolean modified = CopyOnWriteArrayList.this.bulkRemove(
1505 filter, offset, offset + size);
1506 size += (expectedArray = getArray()).length - oldArray.length;
1507 return modified;
1508 }
1509 }
1510
1511 public Spliterator<E> spliterator() {
1512 synchronized (lock) {
1513 return Spliterators.spliterator(
1514 getArrayChecked(), offset, offset + size,
1515 Spliterator.IMMUTABLE | Spliterator.ORDERED);
1516 }
1517 }
1518
1519 }
1520
1521 private static class COWSubListIterator<E> implements ListIterator<E> {
1522 private final ListIterator<E> it;
1523 private final int offset;
1524 private final int size;
1525
1526 COWSubListIterator(List<E> l, int index, int offset, int size) {
1527 this.offset = offset;
1528 this.size = size;
1529 it = l.listIterator(index + offset);
1530 }
1531
1532 public boolean hasNext() {
1533 return nextIndex() < size;
1534 }
1535
1536 public E next() {
1537 if (hasNext())
1538 return it.next();
1539 else
1540 throw new NoSuchElementException();
1541 }
1542
1543 public boolean hasPrevious() {
1544 return previousIndex() >= 0;
1545 }
1546
1547 public E previous() {
1548 if (hasPrevious())
1549 return it.previous();
1558 public int previousIndex() {
1559 return it.previousIndex() - offset;
1560 }
1561
1562 public void remove() {
1563 throw new UnsupportedOperationException();
1564 }
1565
1566 public void set(E e) {
1567 throw new UnsupportedOperationException();
1568 }
1569
1570 public void add(E e) {
1571 throw new UnsupportedOperationException();
1572 }
1573
1574 @Override
1575 @SuppressWarnings("unchecked")
1576 public void forEachRemaining(Consumer<? super E> action) {
1577 Objects.requireNonNull(action);
1578 while (hasNext()) {
1579 action.accept(it.next());
1580 }
1581 }
1582 }
1583
1584 /** Initializes the lock; for use when deserializing or cloning. */
1585 private void resetLock() {
1586 Field lockField = java.security.AccessController.doPrivileged(
1587 (java.security.PrivilegedAction<Field>) () -> {
1588 try {
1589 Field f = CopyOnWriteArrayList.class
1590 .getDeclaredField("lock");
1591 f.setAccessible(true);
1592 return f;
1593 } catch (ReflectiveOperationException e) {
1594 throw new Error(e);
1595 }});
1596 try {
1597 lockField.set(this, new Object());
1598 } catch (IllegalAccessException e) {
|