Path: blob/master/src/java.base/share/classes/java/util/ArrayDeque.java
41152 views
/*1* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.2*3* This code is free software; you can redistribute it and/or modify it4* under the terms of the GNU General Public License version 2 only, as5* published by the Free Software Foundation. Oracle designates this6* particular file as subject to the "Classpath" exception as provided7* by Oracle in the LICENSE file that accompanied this code.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*/2324/*25* This file is available under and governed by the GNU General Public26* License version 2 only, as published by the Free Software Foundation.27* However, the following notice accompanied the original version of this28* file:29*30* Written by Josh Bloch of Google Inc. and released to the public domain,31* as explained at http://creativecommons.org/publicdomain/zero/1.0/.32*/3334package java.util;3536import java.io.Serializable;37import java.util.function.Consumer;38import java.util.function.Predicate;39import jdk.internal.access.SharedSecrets;4041/**42* Resizable-array implementation of the {@link Deque} interface. Array43* deques have no capacity restrictions; they grow as necessary to support44* usage. They are not thread-safe; in the absence of external45* synchronization, they do not support concurrent access by multiple threads.46* Null elements are prohibited. This class is likely to be faster than47* {@link Stack} when used as a stack, and faster than {@link LinkedList}48* when used as a queue.49*50* <p>Most {@code ArrayDeque} operations run in amortized constant time.51* Exceptions include52* {@link #remove(Object) remove},53* {@link #removeFirstOccurrence removeFirstOccurrence},54* {@link #removeLastOccurrence removeLastOccurrence},55* {@link #contains contains},56* {@link #iterator iterator.remove()},57* and the bulk operations, all of which run in linear time.58*59* <p>The iterators returned by this class's {@link #iterator() iterator}60* method are <em>fail-fast</em>: If the deque is modified at any time after61* the iterator is created, in any way except through the iterator's own62* {@code remove} method, the iterator will generally throw a {@link63* ConcurrentModificationException}. Thus, in the face of concurrent64* modification, the iterator fails quickly and cleanly, rather than risking65* arbitrary, non-deterministic behavior at an undetermined time in the66* future.67*68* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed69* as it is, generally speaking, impossible to make any hard guarantees in the70* presence of unsynchronized concurrent modification. Fail-fast iterators71* throw {@code ConcurrentModificationException} on a best-effort basis.72* Therefore, it would be wrong to write a program that depended on this73* exception for its correctness: <i>the fail-fast behavior of iterators74* should be used only to detect bugs.</i>75*76* <p>This class and its iterator implement all of the77* <em>optional</em> methods of the {@link Collection} and {@link78* Iterator} interfaces.79*80* <p>This class is a member of the81* <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">82* Java Collections Framework</a>.83*84* @author Josh Bloch and Doug Lea85* @param <E> the type of elements held in this deque86* @since 1.687*/88public class ArrayDeque<E> extends AbstractCollection<E>89implements Deque<E>, Cloneable, Serializable90{91/*92* VMs excel at optimizing simple array loops where indices are93* incrementing or decrementing over a valid slice, e.g.94*95* for (int i = start; i < end; i++) ... elements[i]96*97* Because in a circular array, elements are in general stored in98* two disjoint such slices, we help the VM by writing unusual99* nested loops for all traversals over the elements. Having only100* one hot inner loop body instead of two or three eases human101* maintenance and encourages VM loop inlining into the caller.102*/103104/**105* The array in which the elements of the deque are stored.106* All array cells not holding deque elements are always null.107* The array always has at least one null slot (at tail).108*/109transient Object[] elements;110111/**112* The index of the element at the head of the deque (which is the113* element that would be removed by remove() or pop()); or an114* arbitrary number 0 <= head < elements.length equal to tail if115* the deque is empty.116*/117transient int head;118119/**120* The index at which the next element would be added to the tail121* of the deque (via addLast(E), add(E), or push(E));122* elements[tail] is always null.123*/124transient int tail;125126/**127* The maximum size of array to allocate.128* Some VMs reserve some header words in an array.129* Attempts to allocate larger arrays may result in130* OutOfMemoryError: Requested array size exceeds VM limit131*/132private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;133134/**135* Increases the capacity of this deque by at least the given amount.136*137* @param needed the required minimum extra capacity; must be positive138*/139private void grow(int needed) {140// overflow-conscious code141final int oldCapacity = elements.length;142int newCapacity;143// Double capacity if small; else grow by 50%144int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);145if (jump < needed146|| (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)147newCapacity = newCapacity(needed, jump);148final Object[] es = elements = Arrays.copyOf(elements, newCapacity);149// Exceptionally, here tail == head needs to be disambiguated150if (tail < head || (tail == head && es[head] != null)) {151// wrap around; slide first leg forward to end of array152int newSpace = newCapacity - oldCapacity;153System.arraycopy(es, head,154es, head + newSpace,155oldCapacity - head);156for (int i = head, to = (head += newSpace); i < to; i++)157es[i] = null;158}159}160161/** Capacity calculation for edge conditions, especially overflow. */162private int newCapacity(int needed, int jump) {163final int oldCapacity = elements.length, minCapacity;164if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {165if (minCapacity < 0)166throw new IllegalStateException("Sorry, deque too big");167return Integer.MAX_VALUE;168}169if (needed > jump)170return minCapacity;171return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)172? oldCapacity + jump173: MAX_ARRAY_SIZE;174}175176/**177* Constructs an empty array deque with an initial capacity178* sufficient to hold 16 elements.179*/180public ArrayDeque() {181elements = new Object[16 + 1];182}183184/**185* Constructs an empty array deque with an initial capacity186* sufficient to hold the specified number of elements.187*188* @param numElements lower bound on initial capacity of the deque189*/190public ArrayDeque(int numElements) {191elements =192new Object[(numElements < 1) ? 1 :193(numElements == Integer.MAX_VALUE) ? Integer.MAX_VALUE :194numElements + 1];195}196197/**198* Constructs a deque containing the elements of the specified199* collection, in the order they are returned by the collection's200* iterator. (The first element returned by the collection's201* iterator becomes the first element, or <i>front</i> of the202* deque.)203*204* @param c the collection whose elements are to be placed into the deque205* @throws NullPointerException if the specified collection is null206*/207public ArrayDeque(Collection<? extends E> c) {208this(c.size());209copyElements(c);210}211212/**213* Circularly increments i, mod modulus.214* Precondition and postcondition: 0 <= i < modulus.215*/216static final int inc(int i, int modulus) {217if (++i >= modulus) i = 0;218return i;219}220221/**222* Circularly decrements i, mod modulus.223* Precondition and postcondition: 0 <= i < modulus.224*/225static final int dec(int i, int modulus) {226if (--i < 0) i = modulus - 1;227return i;228}229230/**231* Circularly adds the given distance to index i, mod modulus.232* Precondition: 0 <= i < modulus, 0 <= distance <= modulus.233* @return index 0 <= i < modulus234*/235static final int inc(int i, int distance, int modulus) {236if ((i += distance) - modulus >= 0) i -= modulus;237return i;238}239240/**241* Subtracts j from i, mod modulus.242* Index i must be logically ahead of index j.243* Precondition: 0 <= i < modulus, 0 <= j < modulus.244* @return the "circular distance" from j to i; corner case i == j245* is disambiguated to "empty", returning 0.246*/247static final int sub(int i, int j, int modulus) {248if ((i -= j) < 0) i += modulus;249return i;250}251252/**253* Returns element at array index i.254* This is a slight abuse of generics, accepted by javac.255*/256@SuppressWarnings("unchecked")257static final <E> E elementAt(Object[] es, int i) {258return (E) es[i];259}260261/**262* A version of elementAt that checks for null elements.263* This check doesn't catch all possible comodifications,264* but does catch ones that corrupt traversal.265*/266static final <E> E nonNullElementAt(Object[] es, int i) {267@SuppressWarnings("unchecked") E e = (E) es[i];268if (e == null)269throw new ConcurrentModificationException();270return e;271}272273// The main insertion and extraction methods are addFirst,274// addLast, pollFirst, pollLast. The other methods are defined in275// terms of these.276277/**278* Inserts the specified element at the front of this deque.279*280* @param e the element to add281* @throws NullPointerException if the specified element is null282*/283public void addFirst(E e) {284if (e == null)285throw new NullPointerException();286final Object[] es = elements;287es[head = dec(head, es.length)] = e;288if (head == tail)289grow(1);290}291292/**293* Inserts the specified element at the end of this deque.294*295* <p>This method is equivalent to {@link #add}.296*297* @param e the element to add298* @throws NullPointerException if the specified element is null299*/300public void addLast(E e) {301if (e == null)302throw new NullPointerException();303final Object[] es = elements;304es[tail] = e;305if (head == (tail = inc(tail, es.length)))306grow(1);307}308309/**310* Adds all of the elements in the specified collection at the end311* of this deque, as if by calling {@link #addLast} on each one,312* in the order that they are returned by the collection's iterator.313*314* @param c the elements to be inserted into this deque315* @return {@code true} if this deque changed as a result of the call316* @throws NullPointerException if the specified collection or any317* of its elements are null318*/319public boolean addAll(Collection<? extends E> c) {320final int s, needed;321if ((needed = (s = size()) + c.size() + 1 - elements.length) > 0)322grow(needed);323copyElements(c);324return size() > s;325}326327private void copyElements(Collection<? extends E> c) {328c.forEach(this::addLast);329}330331/**332* Inserts the specified element at the front of this deque.333*334* @param e the element to add335* @return {@code true} (as specified by {@link Deque#offerFirst})336* @throws NullPointerException if the specified element is null337*/338public boolean offerFirst(E e) {339addFirst(e);340return true;341}342343/**344* Inserts the specified element at the end of this deque.345*346* @param e the element to add347* @return {@code true} (as specified by {@link Deque#offerLast})348* @throws NullPointerException if the specified element is null349*/350public boolean offerLast(E e) {351addLast(e);352return true;353}354355/**356* @throws NoSuchElementException {@inheritDoc}357*/358public E removeFirst() {359E e = pollFirst();360if (e == null)361throw new NoSuchElementException();362return e;363}364365/**366* @throws NoSuchElementException {@inheritDoc}367*/368public E removeLast() {369E e = pollLast();370if (e == null)371throw new NoSuchElementException();372return e;373}374375public E pollFirst() {376final Object[] es;377final int h;378E e = elementAt(es = elements, h = head);379if (e != null) {380es[h] = null;381head = inc(h, es.length);382}383return e;384}385386public E pollLast() {387final Object[] es;388final int t;389E e = elementAt(es = elements, t = dec(tail, es.length));390if (e != null)391es[tail = t] = null;392return e;393}394395/**396* @throws NoSuchElementException {@inheritDoc}397*/398public E getFirst() {399E e = elementAt(elements, head);400if (e == null)401throw new NoSuchElementException();402return e;403}404405/**406* @throws NoSuchElementException {@inheritDoc}407*/408public E getLast() {409final Object[] es = elements;410E e = elementAt(es, dec(tail, es.length));411if (e == null)412throw new NoSuchElementException();413return e;414}415416public E peekFirst() {417return elementAt(elements, head);418}419420public E peekLast() {421final Object[] es;422return elementAt(es = elements, dec(tail, es.length));423}424425/**426* Removes the first occurrence of the specified element in this427* deque (when traversing the deque from head to tail).428* If the deque does not contain the element, it is unchanged.429* More formally, removes the first element {@code e} such that430* {@code o.equals(e)} (if such an element exists).431* Returns {@code true} if this deque contained the specified element432* (or equivalently, if this deque changed as a result of the call).433*434* @param o element to be removed from this deque, if present435* @return {@code true} if the deque contained the specified element436*/437public boolean removeFirstOccurrence(Object o) {438if (o != null) {439final Object[] es = elements;440for (int i = head, end = tail, to = (i <= end) ? end : es.length;441; i = 0, to = end) {442for (; i < to; i++)443if (o.equals(es[i])) {444delete(i);445return true;446}447if (to == end) break;448}449}450return false;451}452453/**454* Removes the last occurrence of the specified element in this455* deque (when traversing the deque from head to tail).456* If the deque does not contain the element, it is unchanged.457* More formally, removes the last element {@code e} such that458* {@code o.equals(e)} (if such an element exists).459* Returns {@code true} if this deque contained the specified element460* (or equivalently, if this deque changed as a result of the call).461*462* @param o element to be removed from this deque, if present463* @return {@code true} if the deque contained the specified element464*/465public boolean removeLastOccurrence(Object o) {466if (o != null) {467final Object[] es = elements;468for (int i = tail, end = head, to = (i >= end) ? end : 0;469; i = es.length, to = end) {470for (i--; i > to - 1; i--)471if (o.equals(es[i])) {472delete(i);473return true;474}475if (to == end) break;476}477}478return false;479}480481// *** Queue methods ***482483/**484* Inserts the specified element at the end of this deque.485*486* <p>This method is equivalent to {@link #addLast}.487*488* @param e the element to add489* @return {@code true} (as specified by {@link Collection#add})490* @throws NullPointerException if the specified element is null491*/492public boolean add(E e) {493addLast(e);494return true;495}496497/**498* Inserts the specified element at the end of this deque.499*500* <p>This method is equivalent to {@link #offerLast}.501*502* @param e the element to add503* @return {@code true} (as specified by {@link Queue#offer})504* @throws NullPointerException if the specified element is null505*/506public boolean offer(E e) {507return offerLast(e);508}509510/**511* Retrieves and removes the head of the queue represented by this deque.512*513* This method differs from {@link #poll() poll()} only in that it514* throws an exception if this deque is empty.515*516* <p>This method is equivalent to {@link #removeFirst}.517*518* @return the head of the queue represented by this deque519* @throws NoSuchElementException {@inheritDoc}520*/521public E remove() {522return removeFirst();523}524525/**526* Retrieves and removes the head of the queue represented by this deque527* (in other words, the first element of this deque), or returns528* {@code null} if this deque is empty.529*530* <p>This method is equivalent to {@link #pollFirst}.531*532* @return the head of the queue represented by this deque, or533* {@code null} if this deque is empty534*/535public E poll() {536return pollFirst();537}538539/**540* Retrieves, but does not remove, the head of the queue represented by541* this deque. This method differs from {@link #peek peek} only in542* that it throws an exception if this deque is empty.543*544* <p>This method is equivalent to {@link #getFirst}.545*546* @return the head of the queue represented by this deque547* @throws NoSuchElementException {@inheritDoc}548*/549public E element() {550return getFirst();551}552553/**554* Retrieves, but does not remove, the head of the queue represented by555* this deque, or returns {@code null} if this deque is empty.556*557* <p>This method is equivalent to {@link #peekFirst}.558*559* @return the head of the queue represented by this deque, or560* {@code null} if this deque is empty561*/562public E peek() {563return peekFirst();564}565566// *** Stack methods ***567568/**569* Pushes an element onto the stack represented by this deque. In other570* words, inserts the element at the front of this deque.571*572* <p>This method is equivalent to {@link #addFirst}.573*574* @param e the element to push575* @throws NullPointerException if the specified element is null576*/577public void push(E e) {578addFirst(e);579}580581/**582* Pops an element from the stack represented by this deque. In other583* words, removes and returns the first element of this deque.584*585* <p>This method is equivalent to {@link #removeFirst()}.586*587* @return the element at the front of this deque (which is the top588* of the stack represented by this deque)589* @throws NoSuchElementException {@inheritDoc}590*/591public E pop() {592return removeFirst();593}594595/**596* Removes the element at the specified position in the elements array.597* This can result in forward or backwards motion of array elements.598* We optimize for least element motion.599*600* <p>This method is called delete rather than remove to emphasize601* that its semantics differ from those of {@link List#remove(int)}.602*603* @return true if elements near tail moved backwards604*/605boolean delete(int i) {606final Object[] es = elements;607final int capacity = es.length;608final int h, t;609// number of elements before to-be-deleted elt610final int front = sub(i, h = head, capacity);611// number of elements after to-be-deleted elt612final int back = sub(t = tail, i, capacity) - 1;613if (front < back) {614// move front elements forwards615if (h <= i) {616System.arraycopy(es, h, es, h + 1, front);617} else { // Wrap around618System.arraycopy(es, 0, es, 1, i);619es[0] = es[capacity - 1];620System.arraycopy(es, h, es, h + 1, front - (i + 1));621}622es[h] = null;623head = inc(h, capacity);624return false;625} else {626// move back elements backwards627tail = dec(t, capacity);628if (i <= tail) {629System.arraycopy(es, i + 1, es, i, back);630} else { // Wrap around631System.arraycopy(es, i + 1, es, i, capacity - (i + 1));632es[capacity - 1] = es[0];633System.arraycopy(es, 1, es, 0, t - 1);634}635es[tail] = null;636return true;637}638}639640// *** Collection Methods ***641642/**643* Returns the number of elements in this deque.644*645* @return the number of elements in this deque646*/647public int size() {648return sub(tail, head, elements.length);649}650651/**652* Returns {@code true} if this deque contains no elements.653*654* @return {@code true} if this deque contains no elements655*/656public boolean isEmpty() {657return head == tail;658}659660/**661* Returns an iterator over the elements in this deque. The elements662* will be ordered from first (head) to last (tail). This is the same663* order that elements would be dequeued (via successive calls to664* {@link #remove} or popped (via successive calls to {@link #pop}).665*666* @return an iterator over the elements in this deque667*/668public Iterator<E> iterator() {669return new DeqIterator();670}671672public Iterator<E> descendingIterator() {673return new DescendingIterator();674}675676private class DeqIterator implements Iterator<E> {677/** Index of element to be returned by subsequent call to next. */678int cursor;679680/** Number of elements yet to be returned. */681int remaining = size();682683/**684* Index of element returned by most recent call to next.685* Reset to -1 if element is deleted by a call to remove.686*/687int lastRet = -1;688689DeqIterator() { cursor = head; }690691public final boolean hasNext() {692return remaining > 0;693}694695public E next() {696if (remaining <= 0)697throw new NoSuchElementException();698final Object[] es = elements;699E e = nonNullElementAt(es, cursor);700cursor = inc(lastRet = cursor, es.length);701remaining--;702return e;703}704705void postDelete(boolean leftShifted) {706if (leftShifted)707cursor = dec(cursor, elements.length);708}709710public final void remove() {711if (lastRet < 0)712throw new IllegalStateException();713postDelete(delete(lastRet));714lastRet = -1;715}716717public void forEachRemaining(Consumer<? super E> action) {718Objects.requireNonNull(action);719int r;720if ((r = remaining) <= 0)721return;722remaining = 0;723final Object[] es = elements;724if (es[cursor] == null || sub(tail, cursor, es.length) != r)725throw new ConcurrentModificationException();726for (int i = cursor, end = tail, to = (i <= end) ? end : es.length;727; i = 0, to = end) {728for (; i < to; i++)729action.accept(elementAt(es, i));730if (to == end) {731if (end != tail)732throw new ConcurrentModificationException();733lastRet = dec(end, es.length);734break;735}736}737}738}739740private class DescendingIterator extends DeqIterator {741DescendingIterator() { cursor = dec(tail, elements.length); }742743public final E next() {744if (remaining <= 0)745throw new NoSuchElementException();746final Object[] es = elements;747E e = nonNullElementAt(es, cursor);748cursor = dec(lastRet = cursor, es.length);749remaining--;750return e;751}752753void postDelete(boolean leftShifted) {754if (!leftShifted)755cursor = inc(cursor, elements.length);756}757758public final void forEachRemaining(Consumer<? super E> action) {759Objects.requireNonNull(action);760int r;761if ((r = remaining) <= 0)762return;763remaining = 0;764final Object[] es = elements;765if (es[cursor] == null || sub(cursor, head, es.length) + 1 != r)766throw new ConcurrentModificationException();767for (int i = cursor, end = head, to = (i >= end) ? end : 0;768; i = es.length - 1, to = end) {769// hotspot generates faster code than for: i >= to !770for (; i > to - 1; i--)771action.accept(elementAt(es, i));772if (to == end) {773if (end != head)774throw new ConcurrentModificationException();775lastRet = end;776break;777}778}779}780}781782/**783* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>784* and <em>fail-fast</em> {@link Spliterator} over the elements in this785* deque.786*787* <p>The {@code Spliterator} reports {@link Spliterator#SIZED},788* {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and789* {@link Spliterator#NONNULL}. Overriding implementations should document790* the reporting of additional characteristic values.791*792* @return a {@code Spliterator} over the elements in this deque793* @since 1.8794*/795public Spliterator<E> spliterator() {796return new DeqSpliterator();797}798799final class DeqSpliterator implements Spliterator<E> {800private int fence; // -1 until first use801private int cursor; // current index, modified on traverse/split802803/** Constructs late-binding spliterator over all elements. */804DeqSpliterator() {805this.fence = -1;806}807808/** Constructs spliterator over the given range. */809DeqSpliterator(int origin, int fence) {810// assert 0 <= origin && origin < elements.length;811// assert 0 <= fence && fence < elements.length;812this.cursor = origin;813this.fence = fence;814}815816/** Ensures late-binding initialization; then returns fence. */817private int getFence() { // force initialization818int t;819if ((t = fence) < 0) {820t = fence = tail;821cursor = head;822}823return t;824}825826public DeqSpliterator trySplit() {827final Object[] es = elements;828final int i, n;829return ((n = sub(getFence(), i = cursor, es.length) >> 1) <= 0)830? null831: new DeqSpliterator(i, cursor = inc(i, n, es.length));832}833834public void forEachRemaining(Consumer<? super E> action) {835if (action == null)836throw new NullPointerException();837final int end = getFence(), cursor = this.cursor;838final Object[] es = elements;839if (cursor != end) {840this.cursor = end;841// null check at both ends of range is sufficient842if (es[cursor] == null || es[dec(end, es.length)] == null)843throw new ConcurrentModificationException();844for (int i = cursor, to = (i <= end) ? end : es.length;845; i = 0, to = end) {846for (; i < to; i++)847action.accept(elementAt(es, i));848if (to == end) break;849}850}851}852853public boolean tryAdvance(Consumer<? super E> action) {854Objects.requireNonNull(action);855final Object[] es = elements;856if (fence < 0) { fence = tail; cursor = head; } // late-binding857final int i;858if ((i = cursor) == fence)859return false;860E e = nonNullElementAt(es, i);861cursor = inc(i, es.length);862action.accept(e);863return true;864}865866public long estimateSize() {867return sub(getFence(), cursor, elements.length);868}869870public int characteristics() {871return Spliterator.NONNULL872| Spliterator.ORDERED873| Spliterator.SIZED874| Spliterator.SUBSIZED;875}876}877878/**879* @throws NullPointerException {@inheritDoc}880*/881public void forEach(Consumer<? super E> action) {882Objects.requireNonNull(action);883final Object[] es = elements;884for (int i = head, end = tail, to = (i <= end) ? end : es.length;885; i = 0, to = end) {886for (; i < to; i++)887action.accept(elementAt(es, i));888if (to == end) {889if (end != tail) throw new ConcurrentModificationException();890break;891}892}893}894895/**896* @throws NullPointerException {@inheritDoc}897*/898public boolean removeIf(Predicate<? super E> filter) {899Objects.requireNonNull(filter);900return bulkRemove(filter);901}902903/**904* @throws NullPointerException {@inheritDoc}905*/906public boolean removeAll(Collection<?> c) {907Objects.requireNonNull(c);908return bulkRemove(e -> c.contains(e));909}910911/**912* @throws NullPointerException {@inheritDoc}913*/914public boolean retainAll(Collection<?> c) {915Objects.requireNonNull(c);916return bulkRemove(e -> !c.contains(e));917}918919/** Implementation of bulk remove methods. */920private boolean bulkRemove(Predicate<? super E> filter) {921final Object[] es = elements;922// Optimize for initial run of survivors923for (int i = head, end = tail, to = (i <= end) ? end : es.length;924; i = 0, to = end) {925for (; i < to; i++)926if (filter.test(elementAt(es, i)))927return bulkRemoveModified(filter, i);928if (to == end) {929if (end != tail) throw new ConcurrentModificationException();930break;931}932}933return false;934}935936// A tiny bit set implementation937938private static long[] nBits(int n) {939return new long[((n - 1) >> 6) + 1];940}941private static void setBit(long[] bits, int i) {942bits[i >> 6] |= 1L << i;943}944private static boolean isClear(long[] bits, int i) {945return (bits[i >> 6] & (1L << i)) == 0;946}947948/**949* Helper for bulkRemove, in case of at least one deletion.950* Tolerate predicates that reentrantly access the collection for951* read (but writers still get CME), so traverse once to find952* elements to delete, a second pass to physically expunge.953*954* @param beg valid index of first element to be deleted955*/956private boolean bulkRemoveModified(957Predicate<? super E> filter, final int beg) {958final Object[] es = elements;959final int capacity = es.length;960final int end = tail;961final long[] deathRow = nBits(sub(end, beg, capacity));962deathRow[0] = 1L; // set bit 0963for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;964; i = 0, to = end, k -= capacity) {965for (; i < to; i++)966if (filter.test(elementAt(es, i)))967setBit(deathRow, i - k);968if (to == end) break;969}970// a two-finger traversal, with hare i reading, tortoise w writing971int w = beg;972for (int i = beg + 1, to = (i <= end) ? end : es.length, k = beg;973; w = 0) { // w rejoins i on second leg974// In this loop, i and w are on the same leg, with i > w975for (; i < to; i++)976if (isClear(deathRow, i - k))977es[w++] = es[i];978if (to == end) break;979// In this loop, w is on the first leg, i on the second980for (i = 0, to = end, k -= capacity; i < to && w < capacity; i++)981if (isClear(deathRow, i - k))982es[w++] = es[i];983if (i >= to) {984if (w == capacity) w = 0; // "corner" case985break;986}987}988if (end != tail) throw new ConcurrentModificationException();989circularClear(es, tail = w, end);990return true;991}992993/**994* Returns {@code true} if this deque contains the specified element.995* More formally, returns {@code true} if and only if this deque contains996* at least one element {@code e} such that {@code o.equals(e)}.997*998* @param o object to be checked for containment in this deque999* @return {@code true} if this deque contains the specified element1000*/1001public boolean contains(Object o) {1002if (o != null) {1003final Object[] es = elements;1004for (int i = head, end = tail, to = (i <= end) ? end : es.length;1005; i = 0, to = end) {1006for (; i < to; i++)1007if (o.equals(es[i]))1008return true;1009if (to == end) break;1010}1011}1012return false;1013}10141015/**1016* Removes a single instance of the specified element from this deque.1017* If the deque does not contain the element, it is unchanged.1018* More formally, removes the first element {@code e} such that1019* {@code o.equals(e)} (if such an element exists).1020* Returns {@code true} if this deque contained the specified element1021* (or equivalently, if this deque changed as a result of the call).1022*1023* <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.1024*1025* @param o element to be removed from this deque, if present1026* @return {@code true} if this deque contained the specified element1027*/1028public boolean remove(Object o) {1029return removeFirstOccurrence(o);1030}10311032/**1033* Removes all of the elements from this deque.1034* The deque will be empty after this call returns.1035*/1036public void clear() {1037circularClear(elements, head, tail);1038head = tail = 0;1039}10401041/**1042* Nulls out slots starting at array index i, upto index end.1043* Condition i == end means "empty" - nothing to do.1044*/1045private static void circularClear(Object[] es, int i, int end) {1046// assert 0 <= i && i < es.length;1047// assert 0 <= end && end < es.length;1048for (int to = (i <= end) ? end : es.length;1049; i = 0, to = end) {1050for (; i < to; i++) es[i] = null;1051if (to == end) break;1052}1053}10541055/**1056* Returns an array containing all of the elements in this deque1057* in proper sequence (from first to last element).1058*1059* <p>The returned array will be "safe" in that no references to it are1060* maintained by this deque. (In other words, this method must allocate1061* a new array). The caller is thus free to modify the returned array.1062*1063* <p>This method acts as bridge between array-based and collection-based1064* APIs.1065*1066* @return an array containing all of the elements in this deque1067*/1068public Object[] toArray() {1069return toArray(Object[].class);1070}10711072private <T> T[] toArray(Class<T[]> klazz) {1073final Object[] es = elements;1074final T[] a;1075final int head = this.head, tail = this.tail, end;1076if ((end = tail + ((head <= tail) ? 0 : es.length)) >= 0) {1077// Uses null extension feature of copyOfRange1078a = Arrays.copyOfRange(es, head, end, klazz);1079} else {1080// integer overflow!1081a = Arrays.copyOfRange(es, 0, end - head, klazz);1082System.arraycopy(es, head, a, 0, es.length - head);1083}1084if (end != tail)1085System.arraycopy(es, 0, a, es.length - head, tail);1086return a;1087}10881089/**1090* Returns an array containing all of the elements in this deque in1091* proper sequence (from first to last element); the runtime type of the1092* returned array is that of the specified array. If the deque fits in1093* the specified array, it is returned therein. Otherwise, a new array1094* is allocated with the runtime type of the specified array and the1095* size of this deque.1096*1097* <p>If this deque fits in the specified array with room to spare1098* (i.e., the array has more elements than this deque), the element in1099* the array immediately following the end of the deque is set to1100* {@code null}.1101*1102* <p>Like the {@link #toArray()} method, this method acts as bridge between1103* array-based and collection-based APIs. Further, this method allows1104* precise control over the runtime type of the output array, and may,1105* under certain circumstances, be used to save allocation costs.1106*1107* <p>Suppose {@code x} is a deque known to contain only strings.1108* The following code can be used to dump the deque into a newly1109* allocated array of {@code String}:1110*1111* <pre> {@code String[] y = x.toArray(new String[0]);}</pre>1112*1113* Note that {@code toArray(new Object[0])} is identical in function to1114* {@code toArray()}.1115*1116* @param a the array into which the elements of the deque are to1117* be stored, if it is big enough; otherwise, a new array of the1118* same runtime type is allocated for this purpose1119* @return an array containing all of the elements in this deque1120* @throws ArrayStoreException if the runtime type of the specified array1121* is not a supertype of the runtime type of every element in1122* this deque1123* @throws NullPointerException if the specified array is null1124*/1125@SuppressWarnings("unchecked")1126public <T> T[] toArray(T[] a) {1127final int size;1128if ((size = size()) > a.length)1129return toArray((Class<T[]>) a.getClass());1130final Object[] es = elements;1131for (int i = head, j = 0, len = Math.min(size, es.length - i);1132; i = 0, len = tail) {1133System.arraycopy(es, i, a, j, len);1134if ((j += len) == size) break;1135}1136if (size < a.length)1137a[size] = null;1138return a;1139}11401141// *** Object methods ***11421143/**1144* Returns a copy of this deque.1145*1146* @return a copy of this deque1147*/1148public ArrayDeque<E> clone() {1149try {1150@SuppressWarnings("unchecked")1151ArrayDeque<E> result = (ArrayDeque<E>) super.clone();1152result.elements = Arrays.copyOf(elements, elements.length);1153return result;1154} catch (CloneNotSupportedException e) {1155throw new AssertionError();1156}1157}11581159@java.io.Serial1160private static final long serialVersionUID = 2340985798034038923L;11611162/**1163* Saves this deque to a stream (that is, serializes it).1164*1165* @param s the stream1166* @throws java.io.IOException if an I/O error occurs1167* @serialData The current size ({@code int}) of the deque,1168* followed by all of its elements (each an object reference) in1169* first-to-last order.1170*/1171@java.io.Serial1172private void writeObject(java.io.ObjectOutputStream s)1173throws java.io.IOException {1174s.defaultWriteObject();11751176// Write out size1177s.writeInt(size());11781179// Write out elements in order.1180final Object[] es = elements;1181for (int i = head, end = tail, to = (i <= end) ? end : es.length;1182; i = 0, to = end) {1183for (; i < to; i++)1184s.writeObject(es[i]);1185if (to == end) break;1186}1187}11881189/**1190* Reconstitutes this deque from a stream (that is, deserializes it).1191* @param s the stream1192* @throws ClassNotFoundException if the class of a serialized object1193* could not be found1194* @throws java.io.IOException if an I/O error occurs1195*/1196@java.io.Serial1197private void readObject(java.io.ObjectInputStream s)1198throws java.io.IOException, ClassNotFoundException {1199s.defaultReadObject();12001201// Read in size and allocate array1202int size = s.readInt();1203SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size + 1);1204elements = new Object[size + 1];1205this.tail = size;12061207// Read in all elements in the proper order.1208for (int i = 0; i < size; i++)1209elements[i] = s.readObject();1210}12111212/** debugging */1213void checkInvariants() {1214// Use head and tail fields with empty slot at tail strategy.1215// head == tail disambiguates to "empty".1216try {1217int capacity = elements.length;1218// assert 0 <= head && head < capacity;1219// assert 0 <= tail && tail < capacity;1220// assert capacity > 0;1221// assert size() < capacity;1222// assert head == tail || elements[head] != null;1223// assert elements[tail] == null;1224// assert head == tail || elements[dec(tail, capacity)] != null;1225} catch (Throwable t) {1226System.err.printf("head=%d tail=%d capacity=%d%n",1227head, tail, elements.length);1228System.err.printf("elements=%s%n",1229Arrays.toString(elements));1230throw t;1231}1232}12331234}123512361237