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