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