Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/util/ArrayList.java
38829 views
/*1* Copyright (c) 1997, 2017, 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 sun.misc.SharedSecrets;3132/**33* Resizable-array implementation of the <tt>List</tt> interface. Implements34* all optional list operations, and permits all elements, including35* <tt>null</tt>. In addition to implementing the <tt>List</tt> interface,36* this class provides methods to manipulate the size of the array that is37* used internally to store the list. (This class is roughly equivalent to38* <tt>Vector</tt>, except that it is unsynchronized.)39*40* <p>The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,41* <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant42* time. The <tt>add</tt> operation runs in <i>amortized constant time</i>,43* that is, adding n elements requires O(n) time. All of the other operations44* run in linear time (roughly speaking). The constant factor is low compared45* to that for the <tt>LinkedList</tt> implementation.46*47* <p>Each <tt>ArrayList</tt> instance has a <i>capacity</i>. The capacity is48* the size of the array used to store the elements in the list. It is always49* at least as large as the list size. As elements are added to an ArrayList,50* its capacity grows automatically. The details of the growth policy are not51* specified beyond the fact that adding an element has constant amortized52* time cost.53*54* <p>An application can increase the capacity of an <tt>ArrayList</tt> instance55* before adding a large number of elements using the <tt>ensureCapacity</tt>56* operation. This may reduce the amount of incremental reallocation.57*58* <p><strong>Note that this implementation is not synchronized.</strong>59* If multiple threads access an <tt>ArrayList</tt> instance concurrently,60* and at least one of the threads modifies the list structurally, it61* <i>must</i> be synchronized externally. (A structural modification is62* any operation that adds or deletes one or more elements, or explicitly63* resizes the backing array; merely setting the value of an element is not64* a structural modification.) This is typically accomplished by65* synchronizing on some object that naturally encapsulates the list.66*67* If no such object exists, the list should be "wrapped" using the68* {@link Collections#synchronizedList Collections.synchronizedList}69* method. This is best done at creation time, to prevent accidental70* unsynchronized access to the list:<pre>71* List list = Collections.synchronizedList(new ArrayList(...));</pre>72*73* <p><a name="fail-fast">74* The iterators returned by this class's {@link #iterator() iterator} and75* {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:</a>76* if the list is structurally modified at any time after the iterator is77* created, in any way except through the iterator's own78* {@link ListIterator#remove() remove} or79* {@link ListIterator#add(Object) add} methods, the iterator will throw a80* {@link ConcurrentModificationException}. Thus, in the face of81* concurrent modification, the iterator fails quickly and cleanly, rather82* than risking arbitrary, non-deterministic behavior at an undetermined83* time in the future.84*85* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed86* as it is, generally speaking, impossible to make any hard guarantees in the87* presence of unsynchronized concurrent modification. Fail-fast iterators88* throw {@code ConcurrentModificationException} on a best-effort basis.89* Therefore, it would be wrong to write a program that depended on this90* exception for its correctness: <i>the fail-fast behavior of iterators91* should be used only to detect bugs.</i>92*93* <p>This class is a member of the94* <a href="{@docRoot}/../technotes/guides/collections/index.html">95* Java Collections Framework</a>.96*97* @author Josh Bloch98* @author Neal Gafter99* @see Collection100* @see List101* @see LinkedList102* @see Vector103* @since 1.2104*/105106public class ArrayList<E> extends AbstractList<E>107implements List<E>, RandomAccess, Cloneable, java.io.Serializable108{109private static final long serialVersionUID = 8683452581122892189L;110111/**112* Default initial capacity.113*/114private static final int DEFAULT_CAPACITY = 10;115116/**117* Shared empty array instance used for empty instances.118*/119private static final Object[] EMPTY_ELEMENTDATA = {};120121/**122* Shared empty array instance used for default sized empty instances. We123* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when124* first element is added.125*/126private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};127128/**129* The array buffer into which the elements of the ArrayList are stored.130* The capacity of the ArrayList is the length of this array buffer. Any131* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA132* will be expanded to DEFAULT_CAPACITY when the first element is added.133*/134transient Object[] elementData; // non-private to simplify nested class access135136/**137* The size of the ArrayList (the number of elements it contains).138*139* @serial140*/141private int size;142143/**144* Constructs an empty list with the specified initial capacity.145*146* @param initialCapacity the initial capacity of the list147* @throws IllegalArgumentException if the specified initial capacity148* is negative149*/150public ArrayList(int initialCapacity) {151if (initialCapacity > 0) {152this.elementData = new Object[initialCapacity];153} else if (initialCapacity == 0) {154this.elementData = EMPTY_ELEMENTDATA;155} else {156throw new IllegalArgumentException("Illegal Capacity: "+157initialCapacity);158}159}160161/**162* Constructs an empty list with an initial capacity of ten.163*/164public ArrayList() {165this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;166}167168/**169* Constructs a list containing the elements of the specified170* collection, in the order they are returned by the collection's171* iterator.172*173* @param c the collection whose elements are to be placed into this list174* @throws NullPointerException if the specified collection is null175*/176public ArrayList(Collection<? extends E> c) {177Object[] a = c.toArray();178if ((size = a.length) != 0) {179if (c.getClass() == ArrayList.class) {180elementData = a;181} else {182elementData = Arrays.copyOf(a, size, Object[].class);183}184} else {185// replace with empty array.186elementData = EMPTY_ELEMENTDATA;187}188}189190/**191* Trims the capacity of this <tt>ArrayList</tt> instance to be the192* list's current size. An application can use this operation to minimize193* the storage of an <tt>ArrayList</tt> instance.194*/195public void trimToSize() {196modCount++;197if (size < elementData.length) {198elementData = (size == 0)199? EMPTY_ELEMENTDATA200: Arrays.copyOf(elementData, size);201}202}203204/**205* Increases the capacity of this <tt>ArrayList</tt> instance, if206* necessary, to ensure that it can hold at least the number of elements207* specified by the minimum capacity argument.208*209* @param minCapacity the desired minimum capacity210*/211public void ensureCapacity(int minCapacity) {212int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)213// any size if not default element table214? 0215// larger than default for default empty table. It's already216// supposed to be at default size.217: DEFAULT_CAPACITY;218219if (minCapacity > minExpand) {220ensureExplicitCapacity(minCapacity);221}222}223224private static int calculateCapacity(Object[] elementData, int minCapacity) {225if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {226return Math.max(DEFAULT_CAPACITY, minCapacity);227}228return minCapacity;229}230231private void ensureCapacityInternal(int minCapacity) {232ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));233}234235private void ensureExplicitCapacity(int minCapacity) {236modCount++;237238// overflow-conscious code239if (minCapacity - elementData.length > 0)240grow(minCapacity);241}242243/**244* The maximum size of array to allocate.245* Some VMs reserve some header words in an array.246* Attempts to allocate larger arrays may result in247* OutOfMemoryError: Requested array size exceeds VM limit248*/249private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;250251/**252* Increases the capacity to ensure that it can hold at least the253* number of elements specified by the minimum capacity argument.254*255* @param minCapacity the desired minimum capacity256*/257private void grow(int minCapacity) {258// overflow-conscious code259int oldCapacity = elementData.length;260int newCapacity = oldCapacity + (oldCapacity >> 1);261if (newCapacity - minCapacity < 0)262newCapacity = minCapacity;263if (newCapacity - MAX_ARRAY_SIZE > 0)264newCapacity = hugeCapacity(minCapacity);265// minCapacity is usually close to size, so this is a win:266elementData = Arrays.copyOf(elementData, newCapacity);267}268269private static int hugeCapacity(int minCapacity) {270if (minCapacity < 0) // overflow271throw new OutOfMemoryError();272return (minCapacity > MAX_ARRAY_SIZE) ?273Integer.MAX_VALUE :274MAX_ARRAY_SIZE;275}276277/**278* Returns the number of elements in this list.279*280* @return the number of elements in this list281*/282public int size() {283return size;284}285286/**287* Returns <tt>true</tt> if this list contains no elements.288*289* @return <tt>true</tt> if this list contains no elements290*/291public boolean isEmpty() {292return size == 0;293}294295/**296* Returns <tt>true</tt> if this list contains the specified element.297* More formally, returns <tt>true</tt> if and only if this list contains298* at least one element <tt>e</tt> such that299* <tt>(o==null ? e==null : o.equals(e))</tt>.300*301* @param o element whose presence in this list is to be tested302* @return <tt>true</tt> if this list contains the specified element303*/304public boolean contains(Object o) {305return indexOf(o) >= 0;306}307308/**309* Returns the index of the first occurrence of the specified element310* in this list, or -1 if this list does not contain the element.311* More formally, returns the lowest index <tt>i</tt> such that312* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,313* or -1 if there is no such index.314*/315public int indexOf(Object o) {316if (o == null) {317for (int i = 0; i < size; i++)318if (elementData[i]==null)319return i;320} else {321for (int i = 0; i < size; i++)322if (o.equals(elementData[i]))323return i;324}325return -1;326}327328/**329* Returns the index of the last occurrence of the specified element330* in this list, or -1 if this list does not contain the element.331* More formally, returns the highest index <tt>i</tt> such that332* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,333* or -1 if there is no such index.334*/335public int lastIndexOf(Object o) {336if (o == null) {337for (int i = size-1; i >= 0; i--)338if (elementData[i]==null)339return i;340} else {341for (int i = size-1; i >= 0; i--)342if (o.equals(elementData[i]))343return i;344}345return -1;346}347348/**349* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The350* elements themselves are not copied.)351*352* @return a clone of this <tt>ArrayList</tt> instance353*/354public Object clone() {355try {356ArrayList<?> v = (ArrayList<?>) super.clone();357v.elementData = Arrays.copyOf(elementData, size);358v.modCount = 0;359return v;360} catch (CloneNotSupportedException e) {361// this shouldn't happen, since we are Cloneable362throw new InternalError(e);363}364}365366/**367* Returns an array containing all of the elements in this list368* in proper sequence (from first to last element).369*370* <p>The returned array will be "safe" in that no references to it are371* maintained by this list. (In other words, this method must allocate372* a new array). The caller is thus free to modify the returned array.373*374* <p>This method acts as bridge between array-based and collection-based375* APIs.376*377* @return an array containing all of the elements in this list in378* proper sequence379*/380public Object[] toArray() {381return Arrays.copyOf(elementData, size);382}383384/**385* Returns an array containing all of the elements in this list in proper386* sequence (from first to last element); the runtime type of the returned387* array is that of the specified array. If the list fits in the388* specified array, it is returned therein. Otherwise, a new array is389* allocated with the runtime type of the specified array and the size of390* this list.391*392* <p>If the list fits in the specified array with room to spare393* (i.e., the array has more elements than the list), the element in394* the array immediately following the end of the collection is set to395* <tt>null</tt>. (This is useful in determining the length of the396* list <i>only</i> if the caller knows that the list does not contain397* any null elements.)398*399* @param a the array into which the elements of the list are to400* be stored, if it is big enough; otherwise, a new array of the401* same runtime type is allocated for this purpose.402* @return an array containing the elements of the list403* @throws ArrayStoreException if the runtime type of the specified array404* is not a supertype of the runtime type of every element in405* this list406* @throws NullPointerException if the specified array is null407*/408@SuppressWarnings("unchecked")409public <T> T[] toArray(T[] a) {410if (a.length < size)411// Make a new array of a's runtime type, but my contents:412return (T[]) Arrays.copyOf(elementData, size, a.getClass());413System.arraycopy(elementData, 0, a, 0, size);414if (a.length > size)415a[size] = null;416return a;417}418419// Positional Access Operations420421@SuppressWarnings("unchecked")422E elementData(int index) {423return (E) elementData[index];424}425426/**427* Returns the element at the specified position in this list.428*429* @param index index of the element to return430* @return the element at the specified position in this list431* @throws IndexOutOfBoundsException {@inheritDoc}432*/433public E get(int index) {434rangeCheck(index);435436return elementData(index);437}438439/**440* Replaces the element at the specified position in this list with441* the specified element.442*443* @param index index of the element to replace444* @param element element to be stored at the specified position445* @return the element previously at the specified position446* @throws IndexOutOfBoundsException {@inheritDoc}447*/448public E set(int index, E element) {449rangeCheck(index);450451E oldValue = elementData(index);452elementData[index] = element;453return oldValue;454}455456/**457* Appends the specified element to the end of this list.458*459* @param e element to be appended to this list460* @return <tt>true</tt> (as specified by {@link Collection#add})461*/462public boolean add(E e) {463ensureCapacityInternal(size + 1); // Increments modCount!!464elementData[size++] = e;465return true;466}467468/**469* Inserts the specified element at the specified position in this470* list. Shifts the element currently at that position (if any) and471* any subsequent elements to the right (adds one to their indices).472*473* @param index index at which the specified element is to be inserted474* @param element element to be inserted475* @throws IndexOutOfBoundsException {@inheritDoc}476*/477public void add(int index, E element) {478rangeCheckForAdd(index);479480ensureCapacityInternal(size + 1); // Increments modCount!!481System.arraycopy(elementData, index, elementData, index + 1,482size - index);483elementData[index] = element;484size++;485}486487/**488* Removes the element at the specified position in this list.489* Shifts any subsequent elements to the left (subtracts one from their490* indices).491*492* @param index the index of the element to be removed493* @return the element that was removed from the list494* @throws IndexOutOfBoundsException {@inheritDoc}495*/496public E remove(int index) {497rangeCheck(index);498499modCount++;500E oldValue = elementData(index);501502int numMoved = size - index - 1;503if (numMoved > 0)504System.arraycopy(elementData, index+1, elementData, index,505numMoved);506elementData[--size] = null; // clear to let GC do its work507508return oldValue;509}510511/**512* Removes the first occurrence of the specified element from this list,513* if it is present. If the list does not contain the element, it is514* unchanged. More formally, removes the element with the lowest index515* <tt>i</tt> such that516* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>517* (if such an element exists). Returns <tt>true</tt> if this list518* contained the specified element (or equivalently, if this list519* changed as a result of the call).520*521* @param o element to be removed from this list, if present522* @return <tt>true</tt> if this list contained the specified element523*/524public boolean remove(Object o) {525if (o == null) {526for (int index = 0; index < size; index++)527if (elementData[index] == null) {528fastRemove(index);529return true;530}531} else {532for (int index = 0; index < size; index++)533if (o.equals(elementData[index])) {534fastRemove(index);535return true;536}537}538return false;539}540541/*542* Private remove method that skips bounds checking and does not543* return the value removed.544*/545private void fastRemove(int index) {546modCount++;547int numMoved = size - index - 1;548if (numMoved > 0)549System.arraycopy(elementData, index+1, elementData, index,550numMoved);551elementData[--size] = null; // clear to let GC do its work552}553554/**555* Removes all of the elements from this list. The list will556* be empty after this call returns.557*/558public void clear() {559modCount++;560561// clear to let GC do its work562for (int i = 0; i < size; i++)563elementData[i] = null;564565size = 0;566}567568/**569* Appends all of the elements in the specified collection to the end of570* this list, in the order that they are returned by the571* specified collection's Iterator. The behavior of this operation is572* undefined if the specified collection is modified while the operation573* is in progress. (This implies that the behavior of this call is574* undefined if the specified collection is this list, and this575* list is nonempty.)576*577* @param c collection containing elements to be added to this list578* @return <tt>true</tt> if this list changed as a result of the call579* @throws NullPointerException if the specified collection is null580*/581public boolean addAll(Collection<? extends E> c) {582Object[] a = c.toArray();583int numNew = a.length;584ensureCapacityInternal(size + numNew); // Increments modCount585System.arraycopy(a, 0, elementData, size, numNew);586size += numNew;587return numNew != 0;588}589590/**591* Inserts all of the elements in the specified collection into this592* list, starting at the specified position. Shifts the element593* currently at that position (if any) and any subsequent elements to594* the right (increases their indices). The new elements will appear595* in the list in the order that they are returned by the596* specified collection's iterator.597*598* @param index index at which to insert the first element from the599* specified collection600* @param c collection containing elements to be added to this list601* @return <tt>true</tt> if this list changed as a result of the call602* @throws IndexOutOfBoundsException {@inheritDoc}603* @throws NullPointerException if the specified collection is null604*/605public boolean addAll(int index, Collection<? extends E> c) {606rangeCheckForAdd(index);607608Object[] a = c.toArray();609int numNew = a.length;610ensureCapacityInternal(size + numNew); // Increments modCount611612int numMoved = size - index;613if (numMoved > 0)614System.arraycopy(elementData, index, elementData, index + numNew,615numMoved);616617System.arraycopy(a, 0, elementData, index, numNew);618size += numNew;619return numNew != 0;620}621622/**623* Removes from this list all of the elements whose index is between624* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.625* Shifts any succeeding elements to the left (reduces their index).626* This call shortens the list by {@code (toIndex - fromIndex)} elements.627* (If {@code toIndex==fromIndex}, this operation has no effect.)628*629* @throws IndexOutOfBoundsException if {@code fromIndex} or630* {@code toIndex} is out of range631* ({@code fromIndex < 0 ||632* fromIndex >= size() ||633* toIndex > size() ||634* toIndex < fromIndex})635*/636protected void removeRange(int fromIndex, int toIndex) {637modCount++;638int numMoved = size - toIndex;639System.arraycopy(elementData, toIndex, elementData, fromIndex,640numMoved);641642// clear to let GC do its work643int newSize = size - (toIndex-fromIndex);644for (int i = newSize; i < size; i++) {645elementData[i] = null;646}647size = newSize;648}649650/**651* Checks if the given index is in range. If not, throws an appropriate652* runtime exception. This method does *not* check if the index is653* negative: It is always used immediately prior to an array access,654* which throws an ArrayIndexOutOfBoundsException if index is negative.655*/656private void rangeCheck(int index) {657if (index >= size)658throw new IndexOutOfBoundsException(outOfBoundsMsg(index));659}660661/**662* A version of rangeCheck used by add and addAll.663*/664private void rangeCheckForAdd(int index) {665if (index > size || index < 0)666throw new IndexOutOfBoundsException(outOfBoundsMsg(index));667}668669/**670* Constructs an IndexOutOfBoundsException detail message.671* Of the many possible refactorings of the error handling code,672* this "outlining" performs best with both server and client VMs.673*/674private String outOfBoundsMsg(int index) {675return "Index: "+index+", Size: "+size;676}677678/**679* Removes from this list all of its elements that are contained in the680* specified collection.681*682* @param c collection containing elements to be removed from this list683* @return {@code true} if this list changed as a result of the call684* @throws ClassCastException if the class of an element of this list685* is incompatible with the specified collection686* (<a href="Collection.html#optional-restrictions">optional</a>)687* @throws NullPointerException if this list contains a null element and the688* specified collection does not permit null elements689* (<a href="Collection.html#optional-restrictions">optional</a>),690* or if the specified collection is null691* @see Collection#contains(Object)692*/693public boolean removeAll(Collection<?> c) {694Objects.requireNonNull(c);695return batchRemove(c, false);696}697698/**699* Retains only the elements in this list that are contained in the700* specified collection. In other words, removes from this list all701* of its elements that are not contained in the specified collection.702*703* @param c collection containing elements to be retained in this list704* @return {@code true} if this list changed as a result of the call705* @throws ClassCastException if the class of an element of this list706* is incompatible with the specified collection707* (<a href="Collection.html#optional-restrictions">optional</a>)708* @throws NullPointerException if this list contains a null element and the709* specified collection does not permit null elements710* (<a href="Collection.html#optional-restrictions">optional</a>),711* or if the specified collection is null712* @see Collection#contains(Object)713*/714public boolean retainAll(Collection<?> c) {715Objects.requireNonNull(c);716return batchRemove(c, true);717}718719private boolean batchRemove(Collection<?> c, boolean complement) {720final Object[] elementData = this.elementData;721int r = 0, w = 0;722boolean modified = false;723try {724for (; r < size; r++)725if (c.contains(elementData[r]) == complement)726elementData[w++] = elementData[r];727} finally {728// Preserve behavioral compatibility with AbstractCollection,729// even if c.contains() throws.730if (r != size) {731System.arraycopy(elementData, r,732elementData, w,733size - r);734w += size - r;735}736if (w != size) {737// clear to let GC do its work738for (int i = w; i < size; i++)739elementData[i] = null;740modCount += size - w;741size = w;742modified = true;743}744}745return modified;746}747748/**749* Save the state of the <tt>ArrayList</tt> instance to a stream (that750* is, serialize it).751*752* @serialData The length of the array backing the <tt>ArrayList</tt>753* instance is emitted (int), followed by all of its elements754* (each an <tt>Object</tt>) in the proper order.755*/756private void writeObject(java.io.ObjectOutputStream s)757throws java.io.IOException{758// Write out element count, and any hidden stuff759int expectedModCount = modCount;760s.defaultWriteObject();761762// Write out size as capacity for behavioural compatibility with clone()763s.writeInt(size);764765// Write out all elements in the proper order.766for (int i=0; i<size; i++) {767s.writeObject(elementData[i]);768}769770if (modCount != expectedModCount) {771throw new ConcurrentModificationException();772}773}774775/**776* Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,777* deserialize it).778*/779private void readObject(java.io.ObjectInputStream s)780throws java.io.IOException, ClassNotFoundException {781elementData = EMPTY_ELEMENTDATA;782783// Read in size, and any hidden stuff784s.defaultReadObject();785786// Read in capacity787s.readInt(); // ignored788789if (size > 0) {790// be like clone(), allocate array based upon size not capacity791int capacity = calculateCapacity(elementData, size);792SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);793ensureCapacityInternal(size);794795Object[] a = elementData;796// Read in all elements in the proper order.797for (int i=0; i<size; i++) {798a[i] = s.readObject();799}800}801}802803/**804* Returns a list iterator over the elements in this list (in proper805* sequence), starting at the specified position in the list.806* The specified index indicates the first element that would be807* returned by an initial call to {@link ListIterator#next next}.808* An initial call to {@link ListIterator#previous previous} would809* return the element with the specified index minus one.810*811* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.812*813* @throws IndexOutOfBoundsException {@inheritDoc}814*/815public ListIterator<E> listIterator(int index) {816if (index < 0 || index > size)817throw new IndexOutOfBoundsException("Index: "+index);818return new ListItr(index);819}820821/**822* Returns a list iterator over the elements in this list (in proper823* sequence).824*825* <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>.826*827* @see #listIterator(int)828*/829public ListIterator<E> listIterator() {830return new ListItr(0);831}832833/**834* Returns an iterator over the elements in this list in proper sequence.835*836* <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.837*838* @return an iterator over the elements in this list in proper sequence839*/840public Iterator<E> iterator() {841return new Itr();842}843844/**845* An optimized version of AbstractList.Itr846*/847private class Itr implements Iterator<E> {848int cursor; // index of next element to return849int lastRet = -1; // index of last element returned; -1 if no such850int expectedModCount = modCount;851852Itr() {}853854public boolean hasNext() {855return cursor != size;856}857858@SuppressWarnings("unchecked")859public E next() {860checkForComodification();861int i = cursor;862if (i >= size)863throw new NoSuchElementException();864Object[] elementData = ArrayList.this.elementData;865if (i >= elementData.length)866throw new ConcurrentModificationException();867cursor = i + 1;868return (E) elementData[lastRet = i];869}870871public void remove() {872if (lastRet < 0)873throw new IllegalStateException();874checkForComodification();875876try {877ArrayList.this.remove(lastRet);878cursor = lastRet;879lastRet = -1;880expectedModCount = modCount;881} catch (IndexOutOfBoundsException ex) {882throw new ConcurrentModificationException();883}884}885886@Override887@SuppressWarnings("unchecked")888public void forEachRemaining(Consumer<? super E> consumer) {889Objects.requireNonNull(consumer);890final int size = ArrayList.this.size;891int i = cursor;892if (i >= size) {893return;894}895final Object[] elementData = ArrayList.this.elementData;896if (i >= elementData.length) {897throw new ConcurrentModificationException();898}899while (i != size && modCount == expectedModCount) {900consumer.accept((E) elementData[i++]);901}902// update once at end of iteration to reduce heap write traffic903cursor = i;904lastRet = i - 1;905checkForComodification();906}907908final void checkForComodification() {909if (modCount != expectedModCount)910throw new ConcurrentModificationException();911}912}913914/**915* An optimized version of AbstractList.ListItr916*/917private class ListItr extends Itr implements ListIterator<E> {918ListItr(int index) {919super();920cursor = index;921}922923public boolean hasPrevious() {924return cursor != 0;925}926927public int nextIndex() {928return cursor;929}930931public int previousIndex() {932return cursor - 1;933}934935@SuppressWarnings("unchecked")936public E previous() {937checkForComodification();938int i = cursor - 1;939if (i < 0)940throw new NoSuchElementException();941Object[] elementData = ArrayList.this.elementData;942if (i >= elementData.length)943throw new ConcurrentModificationException();944cursor = i;945return (E) elementData[lastRet = i];946}947948public void set(E e) {949if (lastRet < 0)950throw new IllegalStateException();951checkForComodification();952953try {954ArrayList.this.set(lastRet, e);955} catch (IndexOutOfBoundsException ex) {956throw new ConcurrentModificationException();957}958}959960public void add(E e) {961checkForComodification();962963try {964int i = cursor;965ArrayList.this.add(i, e);966cursor = i + 1;967lastRet = -1;968expectedModCount = modCount;969} catch (IndexOutOfBoundsException ex) {970throw new ConcurrentModificationException();971}972}973}974975/**976* Returns a view of the portion of this list between the specified977* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If978* {@code fromIndex} and {@code toIndex} are equal, the returned list is979* empty.) The returned list is backed by this list, so non-structural980* changes in the returned list are reflected in this list, and vice-versa.981* The returned list supports all of the optional list operations.982*983* <p>This method eliminates the need for explicit range operations (of984* the sort that commonly exist for arrays). Any operation that expects985* a list can be used as a range operation by passing a subList view986* instead of a whole list. For example, the following idiom987* removes a range of elements from a list:988* <pre>989* list.subList(from, to).clear();990* </pre>991* Similar idioms may be constructed for {@link #indexOf(Object)} and992* {@link #lastIndexOf(Object)}, and all of the algorithms in the993* {@link Collections} class can be applied to a subList.994*995* <p>The semantics of the list returned by this method become undefined if996* the backing list (i.e., this list) is <i>structurally modified</i> in997* any way other than via the returned list. (Structural modifications are998* those that change the size of this list, or otherwise perturb it in such999* a fashion that iterations in progress may yield incorrect results.)1000*1001* @throws IndexOutOfBoundsException {@inheritDoc}1002* @throws IllegalArgumentException {@inheritDoc}1003*/1004public List<E> subList(int fromIndex, int toIndex) {1005subListRangeCheck(fromIndex, toIndex, size);1006return new SubList(this, 0, fromIndex, toIndex);1007}10081009static void subListRangeCheck(int fromIndex, int toIndex, int size) {1010if (fromIndex < 0)1011throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);1012if (toIndex > size)1013throw new IndexOutOfBoundsException("toIndex = " + toIndex);1014if (fromIndex > toIndex)1015throw new IllegalArgumentException("fromIndex(" + fromIndex +1016") > toIndex(" + toIndex + ")");1017}10181019private class SubList extends AbstractList<E> implements RandomAccess {1020private final AbstractList<E> parent;1021private final int parentOffset;1022private final int offset;1023int size;10241025SubList(AbstractList<E> parent,1026int offset, int fromIndex, int toIndex) {1027this.parent = parent;1028this.parentOffset = fromIndex;1029this.offset = offset + fromIndex;1030this.size = toIndex - fromIndex;1031this.modCount = ArrayList.this.modCount;1032}10331034public E set(int index, E e) {1035rangeCheck(index);1036checkForComodification();1037E oldValue = ArrayList.this.elementData(offset + index);1038ArrayList.this.elementData[offset + index] = e;1039return oldValue;1040}10411042public E get(int index) {1043rangeCheck(index);1044checkForComodification();1045return ArrayList.this.elementData(offset + index);1046}10471048public int size() {1049checkForComodification();1050return this.size;1051}10521053public void add(int index, E e) {1054rangeCheckForAdd(index);1055checkForComodification();1056parent.add(parentOffset + index, e);1057this.modCount = parent.modCount;1058this.size++;1059}10601061public E remove(int index) {1062rangeCheck(index);1063checkForComodification();1064E result = parent.remove(parentOffset + index);1065this.modCount = parent.modCount;1066this.size--;1067return result;1068}10691070protected void removeRange(int fromIndex, int toIndex) {1071checkForComodification();1072parent.removeRange(parentOffset + fromIndex,1073parentOffset + toIndex);1074this.modCount = parent.modCount;1075this.size -= toIndex - fromIndex;1076}10771078public boolean addAll(Collection<? extends E> c) {1079return addAll(this.size, c);1080}10811082public boolean addAll(int index, Collection<? extends E> c) {1083rangeCheckForAdd(index);1084int cSize = c.size();1085if (cSize==0)1086return false;10871088checkForComodification();1089parent.addAll(parentOffset + index, c);1090this.modCount = parent.modCount;1091this.size += cSize;1092return true;1093}10941095public Iterator<E> iterator() {1096return listIterator();1097}10981099public ListIterator<E> listIterator(final int index) {1100checkForComodification();1101rangeCheckForAdd(index);1102final int offset = this.offset;11031104return new ListIterator<E>() {1105int cursor = index;1106int lastRet = -1;1107int expectedModCount = ArrayList.this.modCount;11081109public boolean hasNext() {1110return cursor != SubList.this.size;1111}11121113@SuppressWarnings("unchecked")1114public E next() {1115checkForComodification();1116int i = cursor;1117if (i >= SubList.this.size)1118throw new NoSuchElementException();1119Object[] elementData = ArrayList.this.elementData;1120if (offset + i >= elementData.length)1121throw new ConcurrentModificationException();1122cursor = i + 1;1123return (E) elementData[offset + (lastRet = i)];1124}11251126public boolean hasPrevious() {1127return cursor != 0;1128}11291130@SuppressWarnings("unchecked")1131public E previous() {1132checkForComodification();1133int i = cursor - 1;1134if (i < 0)1135throw new NoSuchElementException();1136Object[] elementData = ArrayList.this.elementData;1137if (offset + i >= elementData.length)1138throw new ConcurrentModificationException();1139cursor = i;1140return (E) elementData[offset + (lastRet = i)];1141}11421143@SuppressWarnings("unchecked")1144public void forEachRemaining(Consumer<? super E> consumer) {1145Objects.requireNonNull(consumer);1146final int size = SubList.this.size;1147int i = cursor;1148if (i >= size) {1149return;1150}1151final Object[] elementData = ArrayList.this.elementData;1152if (offset + i >= elementData.length) {1153throw new ConcurrentModificationException();1154}1155while (i != size && modCount == expectedModCount) {1156consumer.accept((E) elementData[offset + (i++)]);1157}1158// update once at end of iteration to reduce heap write traffic1159lastRet = cursor = i;1160checkForComodification();1161}11621163public int nextIndex() {1164return cursor;1165}11661167public int previousIndex() {1168return cursor - 1;1169}11701171public void remove() {1172if (lastRet < 0)1173throw new IllegalStateException();1174checkForComodification();11751176try {1177SubList.this.remove(lastRet);1178cursor = lastRet;1179lastRet = -1;1180expectedModCount = ArrayList.this.modCount;1181} catch (IndexOutOfBoundsException ex) {1182throw new ConcurrentModificationException();1183}1184}11851186public void set(E e) {1187if (lastRet < 0)1188throw new IllegalStateException();1189checkForComodification();11901191try {1192ArrayList.this.set(offset + lastRet, e);1193} catch (IndexOutOfBoundsException ex) {1194throw new ConcurrentModificationException();1195}1196}11971198public void add(E e) {1199checkForComodification();12001201try {1202int i = cursor;1203SubList.this.add(i, e);1204cursor = i + 1;1205lastRet = -1;1206expectedModCount = ArrayList.this.modCount;1207} catch (IndexOutOfBoundsException ex) {1208throw new ConcurrentModificationException();1209}1210}12111212final void checkForComodification() {1213if (expectedModCount != ArrayList.this.modCount)1214throw new ConcurrentModificationException();1215}1216};1217}12181219public List<E> subList(int fromIndex, int toIndex) {1220subListRangeCheck(fromIndex, toIndex, size);1221return new SubList(this, offset, fromIndex, toIndex);1222}12231224private void rangeCheck(int index) {1225if (index < 0 || index >= this.size)1226throw new IndexOutOfBoundsException(outOfBoundsMsg(index));1227}12281229private void rangeCheckForAdd(int index) {1230if (index < 0 || index > this.size)1231throw new IndexOutOfBoundsException(outOfBoundsMsg(index));1232}12331234private String outOfBoundsMsg(int index) {1235return "Index: "+index+", Size: "+this.size;1236}12371238private void checkForComodification() {1239if (ArrayList.this.modCount != this.modCount)1240throw new ConcurrentModificationException();1241}12421243public Spliterator<E> spliterator() {1244checkForComodification();1245return new ArrayListSpliterator<E>(ArrayList.this, offset,1246offset + this.size, this.modCount);1247}1248}12491250@Override1251public void forEach(Consumer<? super E> action) {1252Objects.requireNonNull(action);1253final int expectedModCount = modCount;1254@SuppressWarnings("unchecked")1255final E[] elementData = (E[]) this.elementData;1256final int size = this.size;1257for (int i=0; modCount == expectedModCount && i < size; i++) {1258action.accept(elementData[i]);1259}1260if (modCount != expectedModCount) {1261throw new ConcurrentModificationException();1262}1263}12641265/**1266* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>1267* and <em>fail-fast</em> {@link Spliterator} over the elements in this1268* list.1269*1270* <p>The {@code Spliterator} reports {@link Spliterator#SIZED},1271* {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}.1272* Overriding implementations should document the reporting of additional1273* characteristic values.1274*1275* @return a {@code Spliterator} over the elements in this list1276* @since 1.81277*/1278@Override1279public Spliterator<E> spliterator() {1280return new ArrayListSpliterator<>(this, 0, -1, 0);1281}12821283/** Index-based split-by-two, lazily initialized Spliterator */1284static final class ArrayListSpliterator<E> implements Spliterator<E> {12851286/*1287* If ArrayLists were immutable, or structurally immutable (no1288* adds, removes, etc), we could implement their spliterators1289* with Arrays.spliterator. Instead we detect as much1290* interference during traversal as practical without1291* sacrificing much performance. We rely primarily on1292* modCounts. These are not guaranteed to detect concurrency1293* violations, and are sometimes overly conservative about1294* within-thread interference, but detect enough problems to1295* be worthwhile in practice. To carry this out, we (1) lazily1296* initialize fence and expectedModCount until the latest1297* point that we need to commit to the state we are checking1298* against; thus improving precision. (This doesn't apply to1299* SubLists, that create spliterators with current non-lazy1300* values). (2) We perform only a single1301* ConcurrentModificationException check at the end of forEach1302* (the most performance-sensitive method). When using forEach1303* (as opposed to iterators), we can normally only detect1304* interference after actions, not before. Further1305* CME-triggering checks apply to all other possible1306* violations of assumptions for example null or too-small1307* elementData array given its size(), that could only have1308* occurred due to interference. This allows the inner loop1309* of forEach to run without any further checks, and1310* simplifies lambda-resolution. While this does entail a1311* number of checks, note that in the common case of1312* list.stream().forEach(a), no checks or other computation1313* occur anywhere other than inside forEach itself. The other1314* less-often-used methods cannot take advantage of most of1315* these streamlinings.1316*/13171318private final ArrayList<E> list;1319private int index; // current index, modified on advance/split1320private int fence; // -1 until used; then one past last index1321private int expectedModCount; // initialized when fence set13221323/** Create new spliterator covering the given range */1324ArrayListSpliterator(ArrayList<E> list, int origin, int fence,1325int expectedModCount) {1326this.list = list; // OK if null unless traversed1327this.index = origin;1328this.fence = fence;1329this.expectedModCount = expectedModCount;1330}13311332private int getFence() { // initialize fence to size on first use1333int hi; // (a specialized variant appears in method forEach)1334ArrayList<E> lst;1335if ((hi = fence) < 0) {1336if ((lst = list) == null)1337hi = fence = 0;1338else {1339expectedModCount = lst.modCount;1340hi = fence = lst.size;1341}1342}1343return hi;1344}13451346public ArrayListSpliterator<E> trySplit() {1347int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;1348return (lo >= mid) ? null : // divide range in half unless too small1349new ArrayListSpliterator<E>(list, lo, index = mid,1350expectedModCount);1351}13521353public boolean tryAdvance(Consumer<? super E> action) {1354if (action == null)1355throw new NullPointerException();1356int hi = getFence(), i = index;1357if (i < hi) {1358index = i + 1;1359@SuppressWarnings("unchecked") E e = (E)list.elementData[i];1360action.accept(e);1361if (list.modCount != expectedModCount)1362throw new ConcurrentModificationException();1363return true;1364}1365return false;1366}13671368public void forEachRemaining(Consumer<? super E> action) {1369int i, hi, mc; // hoist accesses and checks from loop1370ArrayList<E> lst; Object[] a;1371if (action == null)1372throw new NullPointerException();1373if ((lst = list) != null && (a = lst.elementData) != null) {1374if ((hi = fence) < 0) {1375mc = lst.modCount;1376hi = lst.size;1377}1378else1379mc = expectedModCount;1380if ((i = index) >= 0 && (index = hi) <= a.length) {1381for (; i < hi; ++i) {1382@SuppressWarnings("unchecked") E e = (E) a[i];1383action.accept(e);1384}1385if (lst.modCount == mc)1386return;1387}1388}1389throw new ConcurrentModificationException();1390}13911392public long estimateSize() {1393return (long) (getFence() - index);1394}13951396public int characteristics() {1397return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;1398}1399}14001401@Override1402public boolean removeIf(Predicate<? super E> filter) {1403Objects.requireNonNull(filter);1404// figure out which elements are to be removed1405// any exception thrown from the filter predicate at this stage1406// will leave the collection unmodified1407int removeCount = 0;1408final BitSet removeSet = new BitSet(size);1409final int expectedModCount = modCount;1410final int size = this.size;1411for (int i=0; modCount == expectedModCount && i < size; i++) {1412@SuppressWarnings("unchecked")1413final E element = (E) elementData[i];1414if (filter.test(element)) {1415removeSet.set(i);1416removeCount++;1417}1418}1419if (modCount != expectedModCount) {1420throw new ConcurrentModificationException();1421}14221423// shift surviving elements left over the spaces left by removed elements1424final boolean anyToRemove = removeCount > 0;1425if (anyToRemove) {1426final int newSize = size - removeCount;1427for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {1428i = removeSet.nextClearBit(i);1429elementData[j] = elementData[i];1430}1431for (int k=newSize; k < size; k++) {1432elementData[k] = null; // Let gc do its work1433}1434this.size = newSize;1435if (modCount != expectedModCount) {1436throw new ConcurrentModificationException();1437}1438modCount++;1439}14401441return anyToRemove;1442}14431444@Override1445@SuppressWarnings("unchecked")1446public void replaceAll(UnaryOperator<E> operator) {1447Objects.requireNonNull(operator);1448final int expectedModCount = modCount;1449final int size = this.size;1450for (int i=0; modCount == expectedModCount && i < size; i++) {1451elementData[i] = operator.apply((E) elementData[i]);1452}1453if (modCount != expectedModCount) {1454throw new ConcurrentModificationException();1455}1456modCount++;1457}14581459@Override1460@SuppressWarnings("unchecked")1461public void sort(Comparator<? super E> c) {1462final int expectedModCount = modCount;1463Arrays.sort((E[]) elementData, 0, size, c);1464if (modCount != expectedModCount) {1465throw new ConcurrentModificationException();1466}1467modCount++;1468}1469}147014711472