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