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