Path: blob/master/src/java.base/share/classes/java/util/ArrayList.java
41152 views
/*1* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.util;2627import java.util.function.Consumer;28import java.util.function.Predicate;29import java.util.function.UnaryOperator;30import jdk.internal.access.SharedSecrets;31import jdk.internal.util.ArraysSupport;3233/**34* Resizable-array implementation of the {@code List} interface. Implements35* all optional list operations, and permits all elements, including36* {@code null}. In addition to implementing the {@code List} interface,37* this class provides methods to manipulate the size of the array that is38* used internally to store the list. (This class is roughly equivalent to39* {@code Vector}, except that it is unsynchronized.)40*41* <p>The {@code size}, {@code isEmpty}, {@code get}, {@code set},42* {@code iterator}, and {@code listIterator} operations run in constant43* time. The {@code add} operation runs in <i>amortized constant time</i>,44* that is, adding n elements requires O(n) time. All of the other operations45* run in linear time (roughly speaking). The constant factor is low compared46* to that for the {@code LinkedList} implementation.47*48* <p>Each {@code ArrayList} instance has a <i>capacity</i>. The capacity is49* the size of the array used to store the elements in the list. It is always50* at least as large as the list size. As elements are added to an ArrayList,51* its capacity grows automatically. The details of the growth policy are not52* specified beyond the fact that adding an element has constant amortized53* time cost.54*55* <p>An application can increase the capacity of an {@code ArrayList} instance56* before adding a large number of elements using the {@code ensureCapacity}57* operation. This may reduce the amount of incremental reallocation.58*59* <p><strong>Note that this implementation is not synchronized.</strong>60* If multiple threads access an {@code ArrayList} instance concurrently,61* and at least one of the threads modifies the list structurally, it62* <i>must</i> be synchronized externally. (A structural modification is63* any operation that adds or deletes one or more elements, or explicitly64* resizes the backing array; merely setting the value of an element is not65* a structural modification.) This is typically accomplished by66* synchronizing on some object that naturally encapsulates the list.67*68* If no such object exists, the list should be "wrapped" using the69* {@link Collections#synchronizedList Collections.synchronizedList}70* method. This is best done at creation time, to prevent accidental71* unsynchronized access to the list:<pre>72* List list = Collections.synchronizedList(new ArrayList(...));</pre>73*74* <p id="fail-fast">75* The iterators returned by this class's {@link #iterator() iterator} and76* {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:77* if the list is structurally modified at any time after the iterator is78* created, in any way except through the iterator's own79* {@link ListIterator#remove() remove} or80* {@link ListIterator#add(Object) add} methods, the iterator will throw a81* {@link ConcurrentModificationException}. Thus, in the face of82* concurrent modification, the iterator fails quickly and cleanly, rather83* than risking arbitrary, non-deterministic behavior at an undetermined84* time in the future.85*86* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed87* as it is, generally speaking, impossible to make any hard guarantees in the88* presence of unsynchronized concurrent modification. Fail-fast iterators89* throw {@code ConcurrentModificationException} on a best-effort basis.90* Therefore, it would be wrong to write a program that depended on this91* exception for its correctness: <i>the fail-fast behavior of iterators92* should be used only to detect bugs.</i>93*94* <p>This class is a member of the95* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">96* Java Collections Framework</a>.97*98* @param <E> the type of elements in this list99*100* @author Josh Bloch101* @author Neal Gafter102* @see Collection103* @see List104* @see LinkedList105* @see Vector106* @since 1.2107*/108public class ArrayList<E> extends AbstractList<E>109implements List<E>, RandomAccess, Cloneable, java.io.Serializable110{111@java.io.Serial112private static final long serialVersionUID = 8683452581122892189L;113114/**115* Default initial capacity.116*/117private static final int DEFAULT_CAPACITY = 10;118119/**120* Shared empty array instance used for empty instances.121*/122private static final Object[] EMPTY_ELEMENTDATA = {};123124/**125* Shared empty array instance used for default sized empty instances. We126* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when127* first element is added.128*/129private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};130131/**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. Any134* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA135* will be expanded to DEFAULT_CAPACITY when the first element is added.136*/137transient Object[] elementData; // non-private to simplify nested class access138139/**140* The size of the ArrayList (the number of elements it contains).141*142* @serial143*/144private int size;145146/**147* Constructs an empty list with the specified initial capacity.148*149* @param initialCapacity the initial capacity of the list150* @throws IllegalArgumentException if the specified initial capacity151* is negative152*/153public ArrayList(int initialCapacity) {154if (initialCapacity > 0) {155this.elementData = new Object[initialCapacity];156} else if (initialCapacity == 0) {157this.elementData = EMPTY_ELEMENTDATA;158} else {159throw new IllegalArgumentException("Illegal Capacity: "+160initialCapacity);161}162}163164/**165* Constructs an empty list with an initial capacity of ten.166*/167public ArrayList() {168this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;169}170171/**172* Constructs a list containing the elements of the specified173* collection, in the order they are returned by the collection's174* iterator.175*176* @param c the collection whose elements are to be placed into this list177* @throws NullPointerException if the specified collection is null178*/179public ArrayList(Collection<? extends E> c) {180Object[] a = c.toArray();181if ((size = a.length) != 0) {182if (c.getClass() == ArrayList.class) {183elementData = a;184} else {185elementData = Arrays.copyOf(a, size, Object[].class);186}187} else {188// replace with empty array.189elementData = EMPTY_ELEMENTDATA;190}191}192193/**194* Trims the capacity of this {@code ArrayList} instance to be the195* list's current size. An application can use this operation to minimize196* the storage of an {@code ArrayList} instance.197*/198public void trimToSize() {199modCount++;200if (size < elementData.length) {201elementData = (size == 0)202? EMPTY_ELEMENTDATA203: Arrays.copyOf(elementData, size);204}205}206207/**208* Increases the capacity of this {@code ArrayList} instance, if209* necessary, to ensure that it can hold at least the number of elements210* specified by the minimum capacity argument.211*212* @param minCapacity the desired minimum capacity213*/214public void ensureCapacity(int minCapacity) {215if (minCapacity > elementData.length216&& !(elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA217&& minCapacity <= DEFAULT_CAPACITY)) {218modCount++;219grow(minCapacity);220}221}222223/**224* Increases the capacity to ensure that it can hold at least the225* number of elements specified by the minimum capacity argument.226*227* @param minCapacity the desired minimum capacity228* @throws OutOfMemoryError if minCapacity is less than zero229*/230private Object[] grow(int minCapacity) {231int oldCapacity = elementData.length;232if (oldCapacity > 0 || elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {233int newCapacity = ArraysSupport.newLength(oldCapacity,234minCapacity - oldCapacity, /* minimum growth */235oldCapacity >> 1 /* preferred growth */);236return elementData = Arrays.copyOf(elementData, newCapacity);237} else {238return elementData = new Object[Math.max(DEFAULT_CAPACITY, minCapacity)];239}240}241242private Object[] grow() {243return grow(size + 1);244}245246/**247* Returns the number of elements in this list.248*249* @return the number of elements in this list250*/251public int size() {252return size;253}254255/**256* Returns {@code true} if this list contains no elements.257*258* @return {@code true} if this list contains no elements259*/260public boolean isEmpty() {261return size == 0;262}263264/**265* Returns {@code true} if this list contains the specified element.266* More formally, returns {@code true} if and only if this list contains267* at least one element {@code e} such that268* {@code Objects.equals(o, e)}.269*270* @param o element whose presence in this list is to be tested271* @return {@code true} if this list contains the specified element272*/273public boolean contains(Object o) {274return indexOf(o) >= 0;275}276277/**278* Returns the index of the first occurrence of the specified element279* in this list, or -1 if this list does not contain the element.280* More formally, returns the lowest index {@code i} such that281* {@code Objects.equals(o, get(i))},282* or -1 if there is no such index.283*/284public int indexOf(Object o) {285return indexOfRange(o, 0, size);286}287288int indexOfRange(Object o, int start, int end) {289Object[] es = elementData;290if (o == null) {291for (int i = start; i < end; i++) {292if (es[i] == null) {293return i;294}295}296} else {297for (int i = start; i < end; i++) {298if (o.equals(es[i])) {299return i;300}301}302}303return -1;304}305306/**307* Returns the index of the last occurrence of the specified element308* in this list, or -1 if this list does not contain the element.309* More formally, returns the highest index {@code i} such that310* {@code Objects.equals(o, get(i))},311* or -1 if there is no such index.312*/313public int lastIndexOf(Object o) {314return lastIndexOfRange(o, 0, size);315}316317int lastIndexOfRange(Object o, int start, int end) {318Object[] es = elementData;319if (o == null) {320for (int i = end - 1; i >= start; i--) {321if (es[i] == null) {322return i;323}324}325} else {326for (int i = end - 1; i >= start; i--) {327if (o.equals(es[i])) {328return i;329}330}331}332return -1;333}334335/**336* Returns a shallow copy of this {@code ArrayList} instance. (The337* elements themselves are not copied.)338*339* @return a clone of this {@code ArrayList} instance340*/341public Object clone() {342try {343ArrayList<?> v = (ArrayList<?>) super.clone();344v.elementData = Arrays.copyOf(elementData, size);345v.modCount = 0;346return v;347} catch (CloneNotSupportedException e) {348// this shouldn't happen, since we are Cloneable349throw new InternalError(e);350}351}352353/**354* Returns an array containing all of the elements in this list355* in proper sequence (from first to last element).356*357* <p>The returned array will be "safe" in that no references to it are358* maintained by this list. (In other words, this method must allocate359* a new array). The caller is thus free to modify the returned array.360*361* <p>This method acts as bridge between array-based and collection-based362* APIs.363*364* @return an array containing all of the elements in this list in365* proper sequence366*/367public Object[] toArray() {368return Arrays.copyOf(elementData, size);369}370371/**372* Returns an array containing all of the elements in this list in proper373* sequence (from first to last element); the runtime type of the returned374* array is that of the specified array. If the list fits in the375* specified array, it is returned therein. Otherwise, a new array is376* allocated with the runtime type of the specified array and the size of377* this list.378*379* <p>If the list fits in the specified array with room to spare380* (i.e., the array has more elements than the list), the element in381* the array immediately following the end of the collection is set to382* {@code null}. (This is useful in determining the length of the383* list <i>only</i> if the caller knows that the list does not contain384* any null elements.)385*386* @param a the array into which the elements of the list are to387* be stored, if it is big enough; otherwise, a new array of the388* same runtime type is allocated for this purpose.389* @return an array containing the elements of the list390* @throws ArrayStoreException if the runtime type of the specified array391* is not a supertype of the runtime type of every element in392* this list393* @throws NullPointerException if the specified array is null394*/395@SuppressWarnings("unchecked")396public <T> T[] toArray(T[] a) {397if (a.length < size)398// Make a new array of a's runtime type, but my contents:399return (T[]) Arrays.copyOf(elementData, size, a.getClass());400System.arraycopy(elementData, 0, a, 0, size);401if (a.length > size)402a[size] = null;403return a;404}405406// Positional Access Operations407408@SuppressWarnings("unchecked")409E elementData(int index) {410return (E) elementData[index];411}412413@SuppressWarnings("unchecked")414static <E> E elementAt(Object[] es, int index) {415return (E) es[index];416}417418/**419* Returns the element at the specified position in this list.420*421* @param index index of the element to return422* @return the element at the specified position in this list423* @throws IndexOutOfBoundsException {@inheritDoc}424*/425public E get(int index) {426Objects.checkIndex(index, size);427return elementData(index);428}429430/**431* Replaces the element at the specified position in this list with432* the specified element.433*434* @param index index of the element to replace435* @param element element to be stored at the specified position436* @return the element previously at the specified position437* @throws IndexOutOfBoundsException {@inheritDoc}438*/439public E set(int index, E element) {440Objects.checkIndex(index, size);441E oldValue = elementData(index);442elementData[index] = element;443return oldValue;444}445446/**447* This helper method split out from add(E) to keep method448* bytecode size under 35 (the -XX:MaxInlineSize default value),449* which helps when add(E) is called in a C1-compiled loop.450*/451private void add(E e, Object[] elementData, int s) {452if (s == elementData.length)453elementData = grow();454elementData[s] = e;455size = s + 1;456}457458/**459* Appends the specified element to the end of this list.460*461* @param e element to be appended to this list462* @return {@code true} (as specified by {@link Collection#add})463*/464public boolean add(E e) {465modCount++;466add(e, elementData, size);467return true;468}469470/**471* Inserts the specified element at the specified position in this472* list. Shifts the element currently at that position (if any) and473* any subsequent elements to the right (adds one to their indices).474*475* @param index index at which the specified element is to be inserted476* @param element element to be inserted477* @throws IndexOutOfBoundsException {@inheritDoc}478*/479public void add(int index, E element) {480rangeCheckForAdd(index);481modCount++;482final int s;483Object[] elementData;484if ((s = size) == (elementData = this.elementData).length)485elementData = grow();486System.arraycopy(elementData, index,487elementData, index + 1,488s - index);489elementData[index] = element;490size = s + 1;491}492493/**494* Removes the element at the specified position in this list.495* Shifts any subsequent elements to the left (subtracts one from their496* indices).497*498* @param index the index of the element to be removed499* @return the element that was removed from the list500* @throws IndexOutOfBoundsException {@inheritDoc}501*/502public E remove(int index) {503Objects.checkIndex(index, size);504final Object[] es = elementData;505506@SuppressWarnings("unchecked") E oldValue = (E) es[index];507fastRemove(es, index);508509return oldValue;510}511512/**513* {@inheritDoc}514*/515public boolean equals(Object o) {516if (o == this) {517return true;518}519520if (!(o instanceof List)) {521return false;522}523524final int expectedModCount = modCount;525// ArrayList can be subclassed and given arbitrary behavior, but we can526// still deal with the common case where o is ArrayList precisely527boolean equal = (o.getClass() == ArrayList.class)528? equalsArrayList((ArrayList<?>) o)529: equalsRange((List<?>) o, 0, size);530531checkForComodification(expectedModCount);532return equal;533}534535boolean equalsRange(List<?> other, int from, int to) {536final Object[] es = elementData;537if (to > es.length) {538throw new ConcurrentModificationException();539}540var oit = other.iterator();541for (; from < to; from++) {542if (!oit.hasNext() || !Objects.equals(es[from], oit.next())) {543return false;544}545}546return !oit.hasNext();547}548549private boolean equalsArrayList(ArrayList<?> other) {550final int otherModCount = other.modCount;551final int s = size;552boolean equal;553if (equal = (s == other.size)) {554final Object[] otherEs = other.elementData;555final Object[] es = elementData;556if (s > es.length || s > otherEs.length) {557throw new ConcurrentModificationException();558}559for (int i = 0; i < s; i++) {560if (!Objects.equals(es[i], otherEs[i])) {561equal = false;562break;563}564}565}566other.checkForComodification(otherModCount);567return equal;568}569570private void checkForComodification(final int expectedModCount) {571if (modCount != expectedModCount) {572throw new ConcurrentModificationException();573}574}575576/**577* {@inheritDoc}578*/579public int hashCode() {580int expectedModCount = modCount;581int hash = hashCodeRange(0, size);582checkForComodification(expectedModCount);583return hash;584}585586int hashCodeRange(int from, int to) {587final Object[] es = elementData;588if (to > es.length) {589throw new ConcurrentModificationException();590}591int hashCode = 1;592for (int i = from; i < to; i++) {593Object e = es[i];594hashCode = 31 * hashCode + (e == null ? 0 : e.hashCode());595}596return hashCode;597}598599/**600* Removes the first occurrence of the specified element from this list,601* if it is present. If the list does not contain the element, it is602* unchanged. More formally, removes the element with the lowest index603* {@code i} such that604* {@code Objects.equals(o, get(i))}605* (if such an element exists). Returns {@code true} if this list606* contained the specified element (or equivalently, if this list607* changed as a result of the call).608*609* @param o element to be removed from this list, if present610* @return {@code true} if this list contained the specified element611*/612public boolean remove(Object o) {613final Object[] es = elementData;614final int size = this.size;615int i = 0;616found: {617if (o == null) {618for (; i < size; i++)619if (es[i] == null)620break found;621} else {622for (; i < size; i++)623if (o.equals(es[i]))624break found;625}626return false;627}628fastRemove(es, i);629return true;630}631632/**633* Private remove method that skips bounds checking and does not634* return the value removed.635*/636private void fastRemove(Object[] es, int i) {637modCount++;638final int newSize;639if ((newSize = size - 1) > i)640System.arraycopy(es, i + 1, es, i, newSize - i);641es[size = newSize] = null;642}643644/**645* Removes all of the elements from this list. The list will646* be empty after this call returns.647*/648public void clear() {649modCount++;650final Object[] es = elementData;651for (int to = size, i = size = 0; i < to; i++)652es[i] = null;653}654655/**656* Appends all of the elements in the specified collection to the end of657* this list, in the order that they are returned by the658* specified collection's Iterator. The behavior of this operation is659* undefined if the specified collection is modified while the operation660* is in progress. (This implies that the behavior of this call is661* undefined if the specified collection is this list, and this662* list is nonempty.)663*664* @param c collection containing elements to be added to this list665* @return {@code true} if this list changed as a result of the call666* @throws NullPointerException if the specified collection is null667*/668public boolean addAll(Collection<? extends E> c) {669Object[] a = c.toArray();670modCount++;671int numNew = a.length;672if (numNew == 0)673return false;674Object[] elementData;675final int s;676if (numNew > (elementData = this.elementData).length - (s = size))677elementData = grow(s + numNew);678System.arraycopy(a, 0, elementData, s, numNew);679size = s + numNew;680return true;681}682683/**684* Inserts all of the elements in the specified collection into this685* list, starting at the specified position. Shifts the element686* currently at that position (if any) and any subsequent elements to687* the right (increases their indices). The new elements will appear688* in the list in the order that they are returned by the689* specified collection's iterator.690*691* @param index index at which to insert the first element from the692* specified collection693* @param c collection containing elements to be added to this list694* @return {@code true} if this list changed as a result of the call695* @throws IndexOutOfBoundsException {@inheritDoc}696* @throws NullPointerException if the specified collection is null697*/698public boolean addAll(int index, Collection<? extends E> c) {699rangeCheckForAdd(index);700701Object[] a = c.toArray();702modCount++;703int numNew = a.length;704if (numNew == 0)705return false;706Object[] elementData;707final int s;708if (numNew > (elementData = this.elementData).length - (s = size))709elementData = grow(s + numNew);710711int numMoved = s - index;712if (numMoved > 0)713System.arraycopy(elementData, index,714elementData, index + numNew,715numMoved);716System.arraycopy(a, 0, elementData, index, numNew);717size = s + numNew;718return true;719}720721/**722* Removes from this list all of the elements whose index is between723* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.724* Shifts any succeeding elements to the left (reduces their index).725* This call shortens the list by {@code (toIndex - fromIndex)} elements.726* (If {@code toIndex==fromIndex}, this operation has no effect.)727*728* @throws IndexOutOfBoundsException if {@code fromIndex} or729* {@code toIndex} is out of range730* ({@code fromIndex < 0 ||731* toIndex > size() ||732* toIndex < fromIndex})733*/734protected void removeRange(int fromIndex, int toIndex) {735if (fromIndex > toIndex) {736throw new IndexOutOfBoundsException(737outOfBoundsMsg(fromIndex, toIndex));738}739modCount++;740shiftTailOverGap(elementData, fromIndex, toIndex);741}742743/** Erases the gap from lo to hi, by sliding down following elements. */744private void shiftTailOverGap(Object[] es, int lo, int hi) {745System.arraycopy(es, hi, es, lo, size - hi);746for (int to = size, i = (size -= hi - lo); i < to; i++)747es[i] = null;748}749750/**751* A version of rangeCheck used by add and addAll.752*/753private void rangeCheckForAdd(int index) {754if (index > size || index < 0)755throw new IndexOutOfBoundsException(outOfBoundsMsg(index));756}757758/**759* Constructs an IndexOutOfBoundsException detail message.760* Of the many possible refactorings of the error handling code,761* this "outlining" performs best with both server and client VMs.762*/763private String outOfBoundsMsg(int index) {764return "Index: "+index+", Size: "+size;765}766767/**768* A version used in checking (fromIndex > toIndex) condition769*/770private static String outOfBoundsMsg(int fromIndex, int toIndex) {771return "From Index: " + fromIndex + " > To Index: " + toIndex;772}773774/**775* Removes from this list all of its elements that are contained in the776* specified collection.777*778* @param c collection containing elements to be removed from this list779* @return {@code true} if this list changed as a result of the call780* @throws ClassCastException if the class of an element of this list781* is incompatible with the specified collection782* (<a href="Collection.html#optional-restrictions">optional</a>)783* @throws NullPointerException if this list contains a null element and the784* specified collection does not permit null elements785* (<a href="Collection.html#optional-restrictions">optional</a>),786* or if the specified collection is null787* @see Collection#contains(Object)788*/789public boolean removeAll(Collection<?> c) {790return batchRemove(c, false, 0, size);791}792793/**794* Retains only the elements in this list that are contained in the795* specified collection. In other words, removes from this list all796* of its elements that are not contained in the specified collection.797*798* @param c collection containing elements to be retained in this list799* @return {@code true} if this list changed as a result of the call800* @throws ClassCastException if the class of an element of this list801* is incompatible with the specified collection802* (<a href="Collection.html#optional-restrictions">optional</a>)803* @throws NullPointerException if this list contains a null element and the804* specified collection does not permit null elements805* (<a href="Collection.html#optional-restrictions">optional</a>),806* or if the specified collection is null807* @see Collection#contains(Object)808*/809public boolean retainAll(Collection<?> c) {810return batchRemove(c, true, 0, size);811}812813boolean batchRemove(Collection<?> c, boolean complement,814final int from, final int end) {815Objects.requireNonNull(c);816final Object[] es = elementData;817int r;818// Optimize for initial run of survivors819for (r = from;; r++) {820if (r == end)821return false;822if (c.contains(es[r]) != complement)823break;824}825int w = r++;826try {827for (Object e; r < end; r++)828if (c.contains(e = es[r]) == complement)829es[w++] = e;830} catch (Throwable ex) {831// Preserve behavioral compatibility with AbstractCollection,832// even if c.contains() throws.833System.arraycopy(es, r, es, w, end - r);834w += end - r;835throw ex;836} finally {837modCount += end - w;838shiftTailOverGap(es, w, end);839}840return true;841}842843/**844* Saves the state of the {@code ArrayList} instance to a stream845* (that is, serializes it).846*847* @param s the stream848* @throws java.io.IOException if an I/O error occurs849* @serialData The length of the array backing the {@code ArrayList}850* instance is emitted (int), followed by all of its elements851* (each an {@code Object}) in the proper order.852*/853@java.io.Serial854private void writeObject(java.io.ObjectOutputStream s)855throws java.io.IOException {856// Write out element count, and any hidden stuff857int expectedModCount = modCount;858s.defaultWriteObject();859860// Write out size as capacity for behavioral compatibility with clone()861s.writeInt(size);862863// Write out all elements in the proper order.864for (int i=0; i<size; i++) {865s.writeObject(elementData[i]);866}867868if (modCount != expectedModCount) {869throw new ConcurrentModificationException();870}871}872873/**874* Reconstitutes the {@code ArrayList} instance from a stream (that is,875* deserializes it).876* @param s the stream877* @throws ClassNotFoundException if the class of a serialized object878* could not be found879* @throws java.io.IOException if an I/O error occurs880*/881@java.io.Serial882private void readObject(java.io.ObjectInputStream s)883throws java.io.IOException, ClassNotFoundException {884885// Read in size, and any hidden stuff886s.defaultReadObject();887888// Read in capacity889s.readInt(); // ignored890891if (size > 0) {892// like clone(), allocate array based upon size not capacity893SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);894Object[] elements = new Object[size];895896// Read in all elements in the proper order.897for (int i = 0; i < size; i++) {898elements[i] = s.readObject();899}900901elementData = elements;902} else if (size == 0) {903elementData = EMPTY_ELEMENTDATA;904} else {905throw new java.io.InvalidObjectException("Invalid size: " + size);906}907}908909/**910* Returns a list iterator over the elements in this list (in proper911* sequence), starting at the specified position in the list.912* The specified index indicates the first element that would be913* returned by an initial call to {@link ListIterator#next next}.914* An initial call to {@link ListIterator#previous previous} would915* return the element with the specified index minus one.916*917* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.918*919* @throws IndexOutOfBoundsException {@inheritDoc}920*/921public ListIterator<E> listIterator(int index) {922rangeCheckForAdd(index);923return new ListItr(index);924}925926/**927* Returns a list iterator over the elements in this list (in proper928* sequence).929*930* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.931*932* @see #listIterator(int)933*/934public ListIterator<E> listIterator() {935return new ListItr(0);936}937938/**939* Returns an iterator over the elements in this list in proper sequence.940*941* <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.942*943* @return an iterator over the elements in this list in proper sequence944*/945public Iterator<E> iterator() {946return new Itr();947}948949/**950* An optimized version of AbstractList.Itr951*/952private class Itr implements Iterator<E> {953int cursor; // index of next element to return954int lastRet = -1; // index of last element returned; -1 if no such955int expectedModCount = modCount;956957// prevent creating a synthetic constructor958Itr() {}959960public boolean hasNext() {961return cursor != size;962}963964@SuppressWarnings("unchecked")965public E next() {966checkForComodification();967int i = cursor;968if (i >= size)969throw new NoSuchElementException();970Object[] elementData = ArrayList.this.elementData;971if (i >= elementData.length)972throw new ConcurrentModificationException();973cursor = i + 1;974return (E) elementData[lastRet = i];975}976977public void remove() {978if (lastRet < 0)979throw new IllegalStateException();980checkForComodification();981982try {983ArrayList.this.remove(lastRet);984cursor = lastRet;985lastRet = -1;986expectedModCount = modCount;987} catch (IndexOutOfBoundsException ex) {988throw new ConcurrentModificationException();989}990}991992@Override993public void forEachRemaining(Consumer<? super E> action) {994Objects.requireNonNull(action);995final int size = ArrayList.this.size;996int i = cursor;997if (i < size) {998final Object[] es = elementData;999if (i >= es.length)1000throw new ConcurrentModificationException();1001for (; i < size && modCount == expectedModCount; i++)1002action.accept(elementAt(es, i));1003// update once at end to reduce heap write traffic1004cursor = i;1005lastRet = i - 1;1006checkForComodification();1007}1008}10091010final void checkForComodification() {1011if (modCount != expectedModCount)1012throw new ConcurrentModificationException();1013}1014}10151016/**1017* An optimized version of AbstractList.ListItr1018*/1019private class ListItr extends Itr implements ListIterator<E> {1020ListItr(int index) {1021super();1022cursor = index;1023}10241025public boolean hasPrevious() {1026return cursor != 0;1027}10281029public int nextIndex() {1030return cursor;1031}10321033public int previousIndex() {1034return cursor - 1;1035}10361037@SuppressWarnings("unchecked")1038public E previous() {1039checkForComodification();1040int i = cursor - 1;1041if (i < 0)1042throw new NoSuchElementException();1043Object[] elementData = ArrayList.this.elementData;1044if (i >= elementData.length)1045throw new ConcurrentModificationException();1046cursor = i;1047return (E) elementData[lastRet = i];1048}10491050public void set(E e) {1051if (lastRet < 0)1052throw new IllegalStateException();1053checkForComodification();10541055try {1056ArrayList.this.set(lastRet, e);1057} catch (IndexOutOfBoundsException ex) {1058throw new ConcurrentModificationException();1059}1060}10611062public void add(E e) {1063checkForComodification();10641065try {1066int i = cursor;1067ArrayList.this.add(i, e);1068cursor = i + 1;1069lastRet = -1;1070expectedModCount = modCount;1071} catch (IndexOutOfBoundsException ex) {1072throw new ConcurrentModificationException();1073}1074}1075}10761077/**1078* Returns a view of the portion of this list between the specified1079* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If1080* {@code fromIndex} and {@code toIndex} are equal, the returned list is1081* empty.) The returned list is backed by this list, so non-structural1082* changes in the returned list are reflected in this list, and vice-versa.1083* The returned list supports all of the optional list operations.1084*1085* <p>This method eliminates the need for explicit range operations (of1086* the sort that commonly exist for arrays). Any operation that expects1087* a list can be used as a range operation by passing a subList view1088* instead of a whole list. For example, the following idiom1089* removes a range of elements from a list:1090* <pre>1091* list.subList(from, to).clear();1092* </pre>1093* Similar idioms may be constructed for {@link #indexOf(Object)} and1094* {@link #lastIndexOf(Object)}, and all of the algorithms in the1095* {@link Collections} class can be applied to a subList.1096*1097* <p>The semantics of the list returned by this method become undefined if1098* the backing list (i.e., this list) is <i>structurally modified</i> in1099* any way other than via the returned list. (Structural modifications are1100* those that change the size of this list, or otherwise perturb it in such1101* a fashion that iterations in progress may yield incorrect results.)1102*1103* @throws IndexOutOfBoundsException {@inheritDoc}1104* @throws IllegalArgumentException {@inheritDoc}1105*/1106public List<E> subList(int fromIndex, int toIndex) {1107subListRangeCheck(fromIndex, toIndex, size);1108return new SubList<>(this, fromIndex, toIndex);1109}11101111private static class SubList<E> extends AbstractList<E> implements RandomAccess {1112private final ArrayList<E> root;1113private final SubList<E> parent;1114private final int offset;1115private int size;11161117/**1118* Constructs a sublist of an arbitrary ArrayList.1119*/1120public SubList(ArrayList<E> root, int fromIndex, int toIndex) {1121this.root = root;1122this.parent = null;1123this.offset = fromIndex;1124this.size = toIndex - fromIndex;1125this.modCount = root.modCount;1126}11271128/**1129* Constructs a sublist of another SubList.1130*/1131private SubList(SubList<E> parent, int fromIndex, int toIndex) {1132this.root = parent.root;1133this.parent = parent;1134this.offset = parent.offset + fromIndex;1135this.size = toIndex - fromIndex;1136this.modCount = parent.modCount;1137}11381139public E set(int index, E element) {1140Objects.checkIndex(index, size);1141checkForComodification();1142E oldValue = root.elementData(offset + index);1143root.elementData[offset + index] = element;1144return oldValue;1145}11461147public E get(int index) {1148Objects.checkIndex(index, size);1149checkForComodification();1150return root.elementData(offset + index);1151}11521153public int size() {1154checkForComodification();1155return size;1156}11571158public void add(int index, E element) {1159rangeCheckForAdd(index);1160checkForComodification();1161root.add(offset + index, element);1162updateSizeAndModCount(1);1163}11641165public E remove(int index) {1166Objects.checkIndex(index, size);1167checkForComodification();1168E result = root.remove(offset + index);1169updateSizeAndModCount(-1);1170return result;1171}11721173protected void removeRange(int fromIndex, int toIndex) {1174checkForComodification();1175root.removeRange(offset + fromIndex, offset + toIndex);1176updateSizeAndModCount(fromIndex - toIndex);1177}11781179public boolean addAll(Collection<? extends E> c) {1180return addAll(this.size, c);1181}11821183public boolean addAll(int index, Collection<? extends E> c) {1184rangeCheckForAdd(index);1185int cSize = c.size();1186if (cSize==0)1187return false;1188checkForComodification();1189root.addAll(offset + index, c);1190updateSizeAndModCount(cSize);1191return true;1192}11931194public void replaceAll(UnaryOperator<E> operator) {1195root.replaceAllRange(operator, offset, offset + size);1196}11971198public boolean removeAll(Collection<?> c) {1199return batchRemove(c, false);1200}12011202public boolean retainAll(Collection<?> c) {1203return batchRemove(c, true);1204}12051206private boolean batchRemove(Collection<?> c, boolean complement) {1207checkForComodification();1208int oldSize = root.size;1209boolean modified =1210root.batchRemove(c, complement, offset, offset + size);1211if (modified)1212updateSizeAndModCount(root.size - oldSize);1213return modified;1214}12151216public boolean removeIf(Predicate<? super E> filter) {1217checkForComodification();1218int oldSize = root.size;1219boolean modified = root.removeIf(filter, offset, offset + size);1220if (modified)1221updateSizeAndModCount(root.size - oldSize);1222return modified;1223}12241225public Object[] toArray() {1226checkForComodification();1227return Arrays.copyOfRange(root.elementData, offset, offset + size);1228}12291230@SuppressWarnings("unchecked")1231public <T> T[] toArray(T[] a) {1232checkForComodification();1233if (a.length < size)1234return (T[]) Arrays.copyOfRange(1235root.elementData, offset, offset + size, a.getClass());1236System.arraycopy(root.elementData, offset, a, 0, size);1237if (a.length > size)1238a[size] = null;1239return a;1240}12411242public boolean equals(Object o) {1243if (o == this) {1244return true;1245}12461247if (!(o instanceof List)) {1248return false;1249}12501251boolean equal = root.equalsRange((List<?>)o, offset, offset + size);1252checkForComodification();1253return equal;1254}12551256public int hashCode() {1257int hash = root.hashCodeRange(offset, offset + size);1258checkForComodification();1259return hash;1260}12611262public int indexOf(Object o) {1263int index = root.indexOfRange(o, offset, offset + size);1264checkForComodification();1265return index >= 0 ? index - offset : -1;1266}12671268public int lastIndexOf(Object o) {1269int index = root.lastIndexOfRange(o, offset, offset + size);1270checkForComodification();1271return index >= 0 ? index - offset : -1;1272}12731274public boolean contains(Object o) {1275return indexOf(o) >= 0;1276}12771278public Iterator<E> iterator() {1279return listIterator();1280}12811282public ListIterator<E> listIterator(int index) {1283checkForComodification();1284rangeCheckForAdd(index);12851286return new ListIterator<E>() {1287int cursor = index;1288int lastRet = -1;1289int expectedModCount = SubList.this.modCount;12901291public boolean hasNext() {1292return cursor != SubList.this.size;1293}12941295@SuppressWarnings("unchecked")1296public E next() {1297checkForComodification();1298int i = cursor;1299if (i >= SubList.this.size)1300throw new NoSuchElementException();1301Object[] elementData = root.elementData;1302if (offset + i >= elementData.length)1303throw new ConcurrentModificationException();1304cursor = i + 1;1305return (E) elementData[offset + (lastRet = i)];1306}13071308public boolean hasPrevious() {1309return cursor != 0;1310}13111312@SuppressWarnings("unchecked")1313public E previous() {1314checkForComodification();1315int i = cursor - 1;1316if (i < 0)1317throw new NoSuchElementException();1318Object[] elementData = root.elementData;1319if (offset + i >= elementData.length)1320throw new ConcurrentModificationException();1321cursor = i;1322return (E) elementData[offset + (lastRet = i)];1323}13241325public void forEachRemaining(Consumer<? super E> action) {1326Objects.requireNonNull(action);1327final int size = SubList.this.size;1328int i = cursor;1329if (i < size) {1330final Object[] es = root.elementData;1331if (offset + i >= es.length)1332throw new ConcurrentModificationException();1333for (; i < size && root.modCount == expectedModCount; i++)1334action.accept(elementAt(es, offset + i));1335// update once at end to reduce heap write traffic1336cursor = i;1337lastRet = i - 1;1338checkForComodification();1339}1340}13411342public int nextIndex() {1343return cursor;1344}13451346public int previousIndex() {1347return cursor - 1;1348}13491350public void remove() {1351if (lastRet < 0)1352throw new IllegalStateException();1353checkForComodification();13541355try {1356SubList.this.remove(lastRet);1357cursor = lastRet;1358lastRet = -1;1359expectedModCount = SubList.this.modCount;1360} catch (IndexOutOfBoundsException ex) {1361throw new ConcurrentModificationException();1362}1363}13641365public void set(E e) {1366if (lastRet < 0)1367throw new IllegalStateException();1368checkForComodification();13691370try {1371root.set(offset + lastRet, e);1372} catch (IndexOutOfBoundsException ex) {1373throw new ConcurrentModificationException();1374}1375}13761377public void add(E e) {1378checkForComodification();13791380try {1381int i = cursor;1382SubList.this.add(i, e);1383cursor = i + 1;1384lastRet = -1;1385expectedModCount = SubList.this.modCount;1386} catch (IndexOutOfBoundsException ex) {1387throw new ConcurrentModificationException();1388}1389}13901391final void checkForComodification() {1392if (root.modCount != expectedModCount)1393throw new ConcurrentModificationException();1394}1395};1396}13971398public List<E> subList(int fromIndex, int toIndex) {1399subListRangeCheck(fromIndex, toIndex, size);1400return new SubList<>(this, fromIndex, toIndex);1401}14021403private void rangeCheckForAdd(int index) {1404if (index < 0 || index > this.size)1405throw new IndexOutOfBoundsException(outOfBoundsMsg(index));1406}14071408private String outOfBoundsMsg(int index) {1409return "Index: "+index+", Size: "+this.size;1410}14111412private void checkForComodification() {1413if (root.modCount != modCount)1414throw new ConcurrentModificationException();1415}14161417private void updateSizeAndModCount(int sizeChange) {1418SubList<E> slist = this;1419do {1420slist.size += sizeChange;1421slist.modCount = root.modCount;1422slist = slist.parent;1423} while (slist != null);1424}14251426public Spliterator<E> spliterator() {1427checkForComodification();14281429// ArrayListSpliterator not used here due to late-binding1430return new Spliterator<E>() {1431private int index = offset; // current index, modified on advance/split1432private int fence = -1; // -1 until used; then one past last index1433private int expectedModCount; // initialized when fence set14341435private int getFence() { // initialize fence to size on first use1436int hi; // (a specialized variant appears in method forEach)1437if ((hi = fence) < 0) {1438expectedModCount = modCount;1439hi = fence = offset + size;1440}1441return hi;1442}14431444public ArrayList<E>.ArrayListSpliterator trySplit() {1445int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;1446// ArrayListSpliterator can be used here as the source is already bound1447return (lo >= mid) ? null : // divide range in half unless too small1448root.new ArrayListSpliterator(lo, index = mid, expectedModCount);1449}14501451public boolean tryAdvance(Consumer<? super E> action) {1452Objects.requireNonNull(action);1453int hi = getFence(), i = index;1454if (i < hi) {1455index = i + 1;1456@SuppressWarnings("unchecked") E e = (E)root.elementData[i];1457action.accept(e);1458if (root.modCount != expectedModCount)1459throw new ConcurrentModificationException();1460return true;1461}1462return false;1463}14641465public void forEachRemaining(Consumer<? super E> action) {1466Objects.requireNonNull(action);1467int i, hi, mc; // hoist accesses and checks from loop1468ArrayList<E> lst = root;1469Object[] a;1470if ((a = lst.elementData) != null) {1471if ((hi = fence) < 0) {1472mc = modCount;1473hi = offset + size;1474}1475else1476mc = expectedModCount;1477if ((i = index) >= 0 && (index = hi) <= a.length) {1478for (; i < hi; ++i) {1479@SuppressWarnings("unchecked") E e = (E) a[i];1480action.accept(e);1481}1482if (lst.modCount == mc)1483return;1484}1485}1486throw new ConcurrentModificationException();1487}14881489public long estimateSize() {1490return getFence() - index;1491}14921493public int characteristics() {1494return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;1495}1496};1497}1498}14991500/**1501* @throws NullPointerException {@inheritDoc}1502*/1503@Override1504public void forEach(Consumer<? super E> action) {1505Objects.requireNonNull(action);1506final int expectedModCount = modCount;1507final Object[] es = elementData;1508final int size = this.size;1509for (int i = 0; modCount == expectedModCount && i < size; i++)1510action.accept(elementAt(es, i));1511if (modCount != expectedModCount)1512throw new ConcurrentModificationException();1513}15141515/**1516* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>1517* and <em>fail-fast</em> {@link Spliterator} over the elements in this1518* list.1519*1520* <p>The {@code Spliterator} reports {@link Spliterator#SIZED},1521* {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.1522* Overriding implementations should document the reporting of additional1523* characteristic values.1524*1525* @return a {@code Spliterator} over the elements in this list1526* @since 1.81527*/1528@Override1529public Spliterator<E> spliterator() {1530return new ArrayListSpliterator(0, -1, 0);1531}15321533/** Index-based split-by-two, lazily initialized Spliterator */1534final class ArrayListSpliterator implements Spliterator<E> {15351536/*1537* If ArrayLists were immutable, or structurally immutable (no1538* adds, removes, etc), we could implement their spliterators1539* with Arrays.spliterator. Instead we detect as much1540* interference during traversal as practical without1541* sacrificing much performance. We rely primarily on1542* modCounts. These are not guaranteed to detect concurrency1543* violations, and are sometimes overly conservative about1544* within-thread interference, but detect enough problems to1545* be worthwhile in practice. To carry this out, we (1) lazily1546* initialize fence and expectedModCount until the latest1547* point that we need to commit to the state we are checking1548* against; thus improving precision. (This doesn't apply to1549* SubLists, that create spliterators with current non-lazy1550* values). (2) We perform only a single1551* ConcurrentModificationException check at the end of forEach1552* (the most performance-sensitive method). When using forEach1553* (as opposed to iterators), we can normally only detect1554* interference after actions, not before. Further1555* CME-triggering checks apply to all other possible1556* violations of assumptions for example null or too-small1557* elementData array given its size(), that could only have1558* occurred due to interference. This allows the inner loop1559* of forEach to run without any further checks, and1560* simplifies lambda-resolution. While this does entail a1561* number of checks, note that in the common case of1562* list.stream().forEach(a), no checks or other computation1563* occur anywhere other than inside forEach itself. The other1564* less-often-used methods cannot take advantage of most of1565* these streamlinings.1566*/15671568private int index; // current index, modified on advance/split1569private int fence; // -1 until used; then one past last index1570private int expectedModCount; // initialized when fence set15711572/** Creates new spliterator covering the given range. */1573ArrayListSpliterator(int origin, int fence, int expectedModCount) {1574this.index = origin;1575this.fence = fence;1576this.expectedModCount = expectedModCount;1577}15781579private int getFence() { // initialize fence to size on first use1580int hi; // (a specialized variant appears in method forEach)1581if ((hi = fence) < 0) {1582expectedModCount = modCount;1583hi = fence = size;1584}1585return hi;1586}15871588public ArrayListSpliterator trySplit() {1589int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;1590return (lo >= mid) ? null : // divide range in half unless too small1591new ArrayListSpliterator(lo, index = mid, expectedModCount);1592}15931594public boolean tryAdvance(Consumer<? super E> action) {1595if (action == null)1596throw new NullPointerException();1597int hi = getFence(), i = index;1598if (i < hi) {1599index = i + 1;1600@SuppressWarnings("unchecked") E e = (E)elementData[i];1601action.accept(e);1602if (modCount != expectedModCount)1603throw new ConcurrentModificationException();1604return true;1605}1606return false;1607}16081609public void forEachRemaining(Consumer<? super E> action) {1610int i, hi, mc; // hoist accesses and checks from loop1611Object[] a;1612if (action == null)1613throw new NullPointerException();1614if ((a = elementData) != null) {1615if ((hi = fence) < 0) {1616mc = modCount;1617hi = size;1618}1619else1620mc = expectedModCount;1621if ((i = index) >= 0 && (index = hi) <= a.length) {1622for (; i < hi; ++i) {1623@SuppressWarnings("unchecked") E e = (E) a[i];1624action.accept(e);1625}1626if (modCount == mc)1627return;1628}1629}1630throw new ConcurrentModificationException();1631}16321633public long estimateSize() {1634return getFence() - index;1635}16361637public int characteristics() {1638return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;1639}1640}16411642// A tiny bit set implementation16431644private static long[] nBits(int n) {1645return new long[((n - 1) >> 6) + 1];1646}1647private static void setBit(long[] bits, int i) {1648bits[i >> 6] |= 1L << i;1649}1650private static boolean isClear(long[] bits, int i) {1651return (bits[i >> 6] & (1L << i)) == 0;1652}16531654/**1655* @throws NullPointerException {@inheritDoc}1656*/1657@Override1658public boolean removeIf(Predicate<? super E> filter) {1659return removeIf(filter, 0, size);1660}16611662/**1663* Removes all elements satisfying the given predicate, from index1664* i (inclusive) to index end (exclusive).1665*/1666boolean removeIf(Predicate<? super E> filter, int i, final int end) {1667Objects.requireNonNull(filter);1668int expectedModCount = modCount;1669final Object[] es = elementData;1670// Optimize for initial run of survivors1671for (; i < end && !filter.test(elementAt(es, i)); i++)1672;1673// Tolerate predicates that reentrantly access the collection for1674// read (but writers still get CME), so traverse once to find1675// elements to delete, a second pass to physically expunge.1676if (i < end) {1677final int beg = i;1678final long[] deathRow = nBits(end - beg);1679deathRow[0] = 1L; // set bit 01680for (i = beg + 1; i < end; i++)1681if (filter.test(elementAt(es, i)))1682setBit(deathRow, i - beg);1683if (modCount != expectedModCount)1684throw new ConcurrentModificationException();1685modCount++;1686int w = beg;1687for (i = beg; i < end; i++)1688if (isClear(deathRow, i - beg))1689es[w++] = es[i];1690shiftTailOverGap(es, w, end);1691return true;1692} else {1693if (modCount != expectedModCount)1694throw new ConcurrentModificationException();1695return false;1696}1697}16981699@Override1700public void replaceAll(UnaryOperator<E> operator) {1701replaceAllRange(operator, 0, size);1702// TODO(8203662): remove increment of modCount from ...1703modCount++;1704}17051706private void replaceAllRange(UnaryOperator<E> operator, int i, int end) {1707Objects.requireNonNull(operator);1708final int expectedModCount = modCount;1709final Object[] es = elementData;1710for (; modCount == expectedModCount && i < end; i++)1711es[i] = operator.apply(elementAt(es, i));1712if (modCount != expectedModCount)1713throw new ConcurrentModificationException();1714}17151716@Override1717@SuppressWarnings("unchecked")1718public void sort(Comparator<? super E> c) {1719final int expectedModCount = modCount;1720Arrays.sort((E[]) elementData, 0, size, c);1721if (modCount != expectedModCount)1722throw new ConcurrentModificationException();1723modCount++;1724}17251726void checkInvariants() {1727// assert size >= 0;1728// assert size == elementData.length || elementData[size] == null;1729}1730}173117321733