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