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