ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk8/java/util/ArrayDeque.java
Revision: 1.2
Committed: Mon Oct 24 23:54:10 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.1: +611 -349 lines
Log Message:
sync with main

File Contents

# User Rev Content
1 jsr166 1.1 /*
2     * Written by Josh Bloch of Google Inc. and released to the public domain,
3     * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
4     */
5    
6     package java.util;
7    
8     import java.io.Serializable;
9     import java.util.function.Consumer;
10 jsr166 1.2 import java.util.function.Predicate;
11     import java.util.function.UnaryOperator;
12 jsr166 1.1
13     /**
14     * Resizable-array implementation of the {@link Deque} interface. Array
15     * deques have no capacity restrictions; they grow as necessary to support
16     * usage. They are not thread-safe; in the absence of external
17     * synchronization, they do not support concurrent access by multiple threads.
18     * Null elements are prohibited. This class is likely to be faster than
19     * {@link Stack} when used as a stack, and faster than {@link LinkedList}
20     * when used as a queue.
21     *
22     * <p>Most {@code ArrayDeque} operations run in amortized constant time.
23     * Exceptions include
24     * {@link #remove(Object) remove},
25     * {@link #removeFirstOccurrence removeFirstOccurrence},
26     * {@link #removeLastOccurrence removeLastOccurrence},
27     * {@link #contains contains},
28     * {@link #iterator iterator.remove()},
29     * and the bulk operations, all of which run in linear time.
30     *
31     * <p>The iterators returned by this class's {@link #iterator() iterator}
32     * method are <em>fail-fast</em>: If the deque is modified at any time after
33     * the iterator is created, in any way except through the iterator's own
34     * {@code remove} method, the iterator will generally throw a {@link
35     * ConcurrentModificationException}. Thus, in the face of concurrent
36     * modification, the iterator fails quickly and cleanly, rather than risking
37     * arbitrary, non-deterministic behavior at an undetermined time in the
38     * future.
39     *
40     * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
41     * as it is, generally speaking, impossible to make any hard guarantees in the
42     * presence of unsynchronized concurrent modification. Fail-fast iterators
43     * throw {@code ConcurrentModificationException} on a best-effort basis.
44     * Therefore, it would be wrong to write a program that depended on this
45     * exception for its correctness: <i>the fail-fast behavior of iterators
46     * should be used only to detect bugs.</i>
47     *
48     * <p>This class and its iterator implement all of the
49     * <em>optional</em> methods of the {@link Collection} and {@link
50     * Iterator} interfaces.
51     *
52     * <p>This class is a member of the
53     * <a href="{@docRoot}/../technotes/guides/collections/index.html">
54     * Java Collections Framework</a>.
55     *
56     * @author Josh Bloch and Doug Lea
57 jsr166 1.2 * @param <E> the type of elements held in this deque
58 jsr166 1.1 * @since 1.6
59     */
60     public class ArrayDeque<E> extends AbstractCollection<E>
61     implements Deque<E>, Cloneable, Serializable
62     {
63     /**
64     * The array in which the elements of the deque are stored.
65 jsr166 1.2 * We guarantee that all array cells not holding deque elements
66     * are always null.
67 jsr166 1.1 */
68 jsr166 1.2 transient Object[] elements;
69 jsr166 1.1
70     /**
71     * The index of the element at the head of the deque (which is the
72     * element that would be removed by remove() or pop()); or an
73 jsr166 1.2 * arbitrary number 0 <= head < elements.length if the deque is empty.
74 jsr166 1.1 */
75     transient int head;
76    
77 jsr166 1.2 /** Number of elements in this collection. */
78     transient int size;
79    
80 jsr166 1.1 /**
81 jsr166 1.2 * The maximum size of array to allocate.
82     * Some VMs reserve some header words in an array.
83     * Attempts to allocate larger arrays may result in
84     * OutOfMemoryError: Requested array size exceeds VM limit
85 jsr166 1.1 */
86 jsr166 1.2 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
87 jsr166 1.1
88     /**
89 jsr166 1.2 * Increases the capacity of this deque by at least the given amount.
90     *
91     * @param needed the required minimum extra capacity; must be positive
92 jsr166 1.1 */
93 jsr166 1.2 private void grow(int needed) {
94     // overflow-conscious code
95     // checkInvariants();
96     int oldCapacity = elements.length;
97     int newCapacity;
98     // Double size if small; else grow by 50%
99     int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
100     if (jump < needed
101     || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
102     newCapacity = newCapacity(needed, jump);
103     elements = Arrays.copyOf(elements, newCapacity);
104     if (oldCapacity - head < size) {
105     // wrap around; slide first leg forward to end of array
106     int newSpace = newCapacity - oldCapacity;
107     System.arraycopy(elements, head,
108     elements, head + newSpace,
109     oldCapacity - head);
110     Arrays.fill(elements, head, head + newSpace, null);
111     head += newSpace;
112     }
113     // checkInvariants();
114     }
115 jsr166 1.1
116 jsr166 1.2 /** Capacity calculation for edge conditions, especially overflow. */
117     private int newCapacity(int needed, int jump) {
118     int oldCapacity = elements.length;
119     int minCapacity;
120     if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
121     if (minCapacity < 0)
122     throw new IllegalStateException("Sorry, deque too big");
123     return Integer.MAX_VALUE;
124     }
125     if (needed > jump)
126     return minCapacity;
127     return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
128     ? oldCapacity + jump
129     : MAX_ARRAY_SIZE;
130     }
131 jsr166 1.1
132     /**
133 jsr166 1.2 * Increases the internal storage of this collection, if necessary,
134     * to ensure that it can hold at least the given number of elements.
135 jsr166 1.1 *
136 jsr166 1.2 * @param minCapacity the desired minimum capacity
137     * @since TBD
138 jsr166 1.1 */
139 jsr166 1.2 /* public */ void ensureCapacity(int minCapacity) {
140     if (minCapacity > elements.length)
141     grow(minCapacity - elements.length);
142     // checkInvariants();
143 jsr166 1.1 }
144    
145     /**
146 jsr166 1.2 * Minimizes the internal storage of this collection.
147     *
148     * @since TBD
149 jsr166 1.1 */
150 jsr166 1.2 /* public */ void trimToSize() {
151     if (size < elements.length) {
152     elements = toArray();
153     head = 0;
154     }
155     // checkInvariants();
156 jsr166 1.1 }
157    
158     /**
159     * Constructs an empty array deque with an initial capacity
160     * sufficient to hold 16 elements.
161     */
162     public ArrayDeque() {
163     elements = new Object[16];
164     }
165    
166     /**
167     * Constructs an empty array deque with an initial capacity
168     * sufficient to hold the specified number of elements.
169     *
170 jsr166 1.2 * @param numElements lower bound on initial capacity of the deque
171 jsr166 1.1 */
172     public ArrayDeque(int numElements) {
173 jsr166 1.2 elements = new Object[numElements];
174 jsr166 1.1 }
175    
176     /**
177     * Constructs a deque containing the elements of the specified
178     * collection, in the order they are returned by the collection's
179     * iterator. (The first element returned by the collection's
180     * iterator becomes the first element, or <i>front</i> of the
181     * deque.)
182     *
183     * @param c the collection whose elements are to be placed into the deque
184     * @throws NullPointerException if the specified collection is null
185     */
186     public ArrayDeque(Collection<? extends E> c) {
187 jsr166 1.2 Object[] elements = c.toArray();
188     // defend against c.toArray (incorrectly) not returning Object[]
189     // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
190     size = elements.length;
191     if (elements.getClass() != Object[].class)
192     elements = Arrays.copyOf(elements, size, Object[].class);
193     for (Object obj : elements)
194     Objects.requireNonNull(obj);
195     this.elements = elements;
196     }
197    
198     /**
199     * Increments i, mod modulus.
200     * Precondition and postcondition: 0 <= i < modulus.
201     */
202     static final int inc(int i, int modulus) {
203     if (++i >= modulus) i = 0;
204     return i;
205     }
206    
207     /**
208     * Decrements i, mod modulus.
209     * Precondition and postcondition: 0 <= i < modulus.
210     */
211     static final int dec(int i, int modulus) {
212     if (--i < 0) i = modulus - 1;
213     return i;
214     }
215    
216     /**
217     * Adds i and j, mod modulus.
218     * Precondition and postcondition: 0 <= i < modulus, 0 <= j <= modulus.
219     */
220     static final int add(int i, int j, int modulus) {
221     if ((i += j) - modulus >= 0) i -= modulus;
222     return i;
223     }
224    
225     /**
226     * Returns the array index of the last element.
227     * May return invalid index -1 if there are no elements.
228     */
229     final int tail() {
230     return add(head, size - 1, elements.length);
231     }
232    
233     /**
234     * Returns element at array index i.
235     */
236     @SuppressWarnings("unchecked")
237     private E elementAt(int i) {
238     return (E) elements[i];
239     }
240    
241     /**
242     * A version of elementAt that checks for null elements.
243     * This check doesn't catch all possible comodifications,
244     * but does catch ones that corrupt traversal.
245     */
246     E checkedElementAt(Object[] elements, int i) {
247     @SuppressWarnings("unchecked") E e = (E) elements[i];
248     if (e == null)
249     throw new ConcurrentModificationException();
250     return e;
251 jsr166 1.1 }
252    
253     // The main insertion and extraction methods are addFirst,
254     // addLast, pollFirst, pollLast. The other methods are defined in
255     // terms of these.
256    
257     /**
258     * Inserts the specified element at the front of this deque.
259     *
260     * @param e the element to add
261     * @throws NullPointerException if the specified element is null
262     */
263     public void addFirst(E e) {
264 jsr166 1.2 // checkInvariants();
265     Objects.requireNonNull(e);
266     Object[] elements;
267     int capacity, h;
268     final int s;
269     if ((s = size) == (capacity = (elements = this.elements).length)) {
270     grow(1);
271     capacity = (elements = this.elements).length;
272     }
273     if ((h = head - 1) < 0) h = capacity - 1;
274     elements[head = h] = e;
275     size = s + 1;
276     // checkInvariants();
277 jsr166 1.1 }
278    
279     /**
280     * Inserts the specified element at the end of this deque.
281     *
282     * <p>This method is equivalent to {@link #add}.
283     *
284     * @param e the element to add
285     * @throws NullPointerException if the specified element is null
286     */
287     public void addLast(E e) {
288 jsr166 1.2 // checkInvariants();
289     Objects.requireNonNull(e);
290     Object[] elements;
291     int capacity;
292     final int s;
293     if ((s = size) == (capacity = (elements = this.elements).length)) {
294     grow(1);
295     capacity = (elements = this.elements).length;
296     }
297     elements[add(head, s, capacity)] = e;
298     size = s + 1;
299     // checkInvariants();
300     }
301    
302     /**
303     * Adds all of the elements in the specified collection at the end
304     * of this deque, as if by calling {@link #addLast} on each one,
305     * in the order that they are returned by the collection's
306     * iterator.
307     *
308     * @param c the elements to be inserted into this deque
309     * @return {@code true} if this deque changed as a result of the call
310     * @throws NullPointerException if the specified collection or any
311     * of its elements are null
312     */
313     public boolean addAll(Collection<? extends E> c) {
314     final int s = size, needed = c.size() - (elements.length - s);
315     if (needed > 0)
316     grow(needed);
317     c.forEach((e) -> addLast(e));
318     // checkInvariants();
319     return size > s;
320 jsr166 1.1 }
321    
322     /**
323     * Inserts the specified element at the front of this deque.
324     *
325     * @param e the element to add
326     * @return {@code true} (as specified by {@link Deque#offerFirst})
327     * @throws NullPointerException if the specified element is null
328     */
329     public boolean offerFirst(E e) {
330     addFirst(e);
331     return true;
332     }
333    
334     /**
335     * Inserts the specified element at the end of this deque.
336     *
337     * @param e the element to add
338     * @return {@code true} (as specified by {@link Deque#offerLast})
339     * @throws NullPointerException if the specified element is null
340     */
341     public boolean offerLast(E e) {
342     addLast(e);
343     return true;
344     }
345    
346     /**
347     * @throws NoSuchElementException {@inheritDoc}
348     */
349     public E removeFirst() {
350 jsr166 1.2 // checkInvariants();
351     E e = pollFirst();
352     if (e == null)
353 jsr166 1.1 throw new NoSuchElementException();
354 jsr166 1.2 return e;
355 jsr166 1.1 }
356    
357     /**
358     * @throws NoSuchElementException {@inheritDoc}
359     */
360     public E removeLast() {
361 jsr166 1.2 // checkInvariants();
362     E e = pollLast();
363     if (e == null)
364 jsr166 1.1 throw new NoSuchElementException();
365 jsr166 1.2 return e;
366 jsr166 1.1 }
367    
368     public E pollFirst() {
369 jsr166 1.2 // checkInvariants();
370     int s, h;
371     if ((s = size) == 0)
372     return null;
373 jsr166 1.1 final Object[] elements = this.elements;
374 jsr166 1.2 @SuppressWarnings("unchecked") E e = (E) elements[h = head];
375     elements[h] = null;
376     if (++h >= elements.length) h = 0;
377     head = h;
378     size = s - 1;
379     return e;
380 jsr166 1.1 }
381    
382     public E pollLast() {
383 jsr166 1.2 // checkInvariants();
384     final int s, tail;
385     if ((s = size) == 0)
386     return null;
387 jsr166 1.1 final Object[] elements = this.elements;
388     @SuppressWarnings("unchecked")
389 jsr166 1.2 E e = (E) elements[tail = add(head, s - 1, elements.length)];
390     elements[tail] = null;
391     size = s - 1;
392     return e;
393 jsr166 1.1 }
394    
395     /**
396     * @throws NoSuchElementException {@inheritDoc}
397     */
398     public E getFirst() {
399 jsr166 1.2 // checkInvariants();
400     if (size == 0) throw new NoSuchElementException();
401     return elementAt(head);
402 jsr166 1.1 }
403    
404     /**
405     * @throws NoSuchElementException {@inheritDoc}
406     */
407     public E getLast() {
408 jsr166 1.2 // checkInvariants();
409     if (size == 0) throw new NoSuchElementException();
410     return elementAt(tail());
411 jsr166 1.1 }
412    
413     public E peekFirst() {
414 jsr166 1.2 // checkInvariants();
415     return (size == 0) ? null : elementAt(head);
416 jsr166 1.1 }
417    
418     public E peekLast() {
419 jsr166 1.2 // checkInvariants();
420     return (size == 0) ? null : elementAt(tail());
421 jsr166 1.1 }
422    
423     /**
424     * Removes the first occurrence of the specified element in this
425     * deque (when traversing the deque from head to tail).
426     * If the deque does not contain the element, it is unchanged.
427     * More formally, removes the first element {@code e} such that
428     * {@code o.equals(e)} (if such an element exists).
429     * Returns {@code true} if this deque contained the specified element
430     * (or equivalently, if this deque changed as a result of the call).
431     *
432     * @param o element to be removed from this deque, if present
433     * @return {@code true} if the deque contained the specified element
434     */
435     public boolean removeFirstOccurrence(Object o) {
436     if (o != null) {
437 jsr166 1.2 final Object[] elements = this.elements;
438     final int capacity = elements.length;
439     int from, end, to, leftover;
440     leftover = (end = (from = head) + size)
441     - (to = (capacity - end >= 0) ? end : capacity);
442     for (;; from = 0, to = leftover, leftover = 0) {
443     for (int i = from; i < to; i++)
444     if (o.equals(elements[i])) {
445     delete(i);
446     return true;
447     }
448     if (leftover == 0) break;
449 jsr166 1.1 }
450     }
451     return false;
452     }
453    
454     /**
455     * Removes the last occurrence of the specified element in this
456     * deque (when traversing the deque from head to tail).
457     * If the deque does not contain the element, it is unchanged.
458     * More formally, removes the last element {@code e} such that
459     * {@code o.equals(e)} (if such an element exists).
460     * Returns {@code true} if this deque contained the specified element
461     * (or equivalently, if this deque changed as a result of the call).
462     *
463     * @param o element to be removed from this deque, if present
464     * @return {@code true} if the deque contained the specified element
465     */
466     public boolean removeLastOccurrence(Object o) {
467     if (o != null) {
468 jsr166 1.2 final Object[] elements = this.elements;
469     final int capacity = elements.length;
470     int from, to, end, leftover;
471     leftover = (to = ((end = (from = tail()) - size) >= -1) ? end : -1) - end;
472     for (;; from = capacity - 1, to = capacity - 1 - leftover, leftover = 0) {
473     for (int i = from; i > to; i--)
474     if (o.equals(elements[i])) {
475     delete(i);
476     return true;
477     }
478     if (leftover == 0) break;
479 jsr166 1.1 }
480     }
481     return false;
482     }
483    
484     // *** Queue methods ***
485    
486     /**
487     * Inserts the specified element at the end of this deque.
488     *
489     * <p>This method is equivalent to {@link #addLast}.
490     *
491     * @param e the element to add
492     * @return {@code true} (as specified by {@link Collection#add})
493     * @throws NullPointerException if the specified element is null
494     */
495     public boolean add(E e) {
496     addLast(e);
497     return true;
498     }
499    
500     /**
501     * Inserts the specified element at the end of this deque.
502     *
503     * <p>This method is equivalent to {@link #offerLast}.
504     *
505     * @param e the element to add
506     * @return {@code true} (as specified by {@link Queue#offer})
507     * @throws NullPointerException if the specified element is null
508     */
509     public boolean offer(E e) {
510     return offerLast(e);
511     }
512    
513     /**
514     * Retrieves and removes the head of the queue represented by this deque.
515     *
516     * This method differs from {@link #poll poll} only in that it throws an
517     * exception if this deque is empty.
518     *
519     * <p>This method is equivalent to {@link #removeFirst}.
520     *
521     * @return the head of the queue represented by this deque
522     * @throws NoSuchElementException {@inheritDoc}
523     */
524     public E remove() {
525     return removeFirst();
526     }
527    
528     /**
529     * Retrieves and removes the head of the queue represented by this deque
530     * (in other words, the first element of this deque), or returns
531     * {@code null} if this deque is empty.
532     *
533     * <p>This method is equivalent to {@link #pollFirst}.
534     *
535     * @return the head of the queue represented by this deque, or
536     * {@code null} if this deque is empty
537     */
538     public E poll() {
539     return pollFirst();
540     }
541    
542     /**
543     * Retrieves, but does not remove, the head of the queue represented by
544     * this deque. This method differs from {@link #peek peek} only in
545     * that it throws an exception if this deque is empty.
546     *
547     * <p>This method is equivalent to {@link #getFirst}.
548     *
549     * @return the head of the queue represented by this deque
550     * @throws NoSuchElementException {@inheritDoc}
551     */
552     public E element() {
553     return getFirst();
554     }
555    
556     /**
557     * Retrieves, but does not remove, the head of the queue represented by
558     * this deque, or returns {@code null} if this deque is empty.
559     *
560     * <p>This method is equivalent to {@link #peekFirst}.
561     *
562     * @return the head of the queue represented by this deque, or
563     * {@code null} if this deque is empty
564     */
565     public E peek() {
566     return peekFirst();
567     }
568    
569     // *** Stack methods ***
570    
571     /**
572     * Pushes an element onto the stack represented by this deque. In other
573     * words, inserts the element at the front of this deque.
574     *
575     * <p>This method is equivalent to {@link #addFirst}.
576     *
577     * @param e the element to push
578     * @throws NullPointerException if the specified element is null
579     */
580     public void push(E e) {
581     addFirst(e);
582     }
583    
584     /**
585     * Pops an element from the stack represented by this deque. In other
586     * words, removes and returns the first element of this deque.
587     *
588     * <p>This method is equivalent to {@link #removeFirst()}.
589     *
590     * @return the element at the front of this deque (which is the top
591     * of the stack represented by this deque)
592     * @throws NoSuchElementException {@inheritDoc}
593     */
594     public E pop() {
595     return removeFirst();
596     }
597    
598     /**
599 jsr166 1.2 * Removes the element at the specified position in the elements array.
600     * This can result in forward or backwards motion of array elements.
601     * We optimize for least element motion.
602 jsr166 1.1 *
603     * <p>This method is called delete rather than remove to emphasize
604     * that its semantics differ from those of {@link List#remove(int)}.
605     *
606     * @return true if elements moved backwards
607     */
608     boolean delete(int i) {
609 jsr166 1.2 // checkInvariants();
610 jsr166 1.1 final Object[] elements = this.elements;
611 jsr166 1.2 final int capacity = elements.length;
612 jsr166 1.1 final int h = head;
613 jsr166 1.2 int front; // number of elements before to-be-deleted elt
614     if ((front = i - h) < 0) front += capacity;
615     final int back = size - front - 1; // number of elements after
616 jsr166 1.1 if (front < back) {
617 jsr166 1.2 // move front elements forwards
618 jsr166 1.1 if (h <= i) {
619     System.arraycopy(elements, h, elements, h + 1, front);
620     } else { // Wrap around
621     System.arraycopy(elements, 0, elements, 1, i);
622 jsr166 1.2 elements[0] = elements[capacity - 1];
623     System.arraycopy(elements, h, elements, h + 1, front - (i + 1));
624 jsr166 1.1 }
625     elements[h] = null;
626 jsr166 1.2 if ((head = (h + 1)) >= capacity) head = 0;
627     size--;
628     // checkInvariants();
629 jsr166 1.1 return false;
630     } else {
631 jsr166 1.2 // move back elements backwards
632     int tail = tail();
633     if (i <= tail) {
634 jsr166 1.1 System.arraycopy(elements, i + 1, elements, i, back);
635     } else { // Wrap around
636 jsr166 1.2 int firstLeg = capacity - (i + 1);
637     System.arraycopy(elements, i + 1, elements, i, firstLeg);
638     elements[capacity - 1] = elements[0];
639     System.arraycopy(elements, 1, elements, 0, back - firstLeg - 1);
640 jsr166 1.1 }
641 jsr166 1.2 elements[tail] = null;
642     size--;
643     // checkInvariants();
644 jsr166 1.1 return true;
645     }
646     }
647    
648     // *** Collection Methods ***
649    
650     /**
651     * Returns the number of elements in this deque.
652     *
653     * @return the number of elements in this deque
654     */
655     public int size() {
656 jsr166 1.2 return size;
657 jsr166 1.1 }
658    
659     /**
660     * Returns {@code true} if this deque contains no elements.
661     *
662     * @return {@code true} if this deque contains no elements
663     */
664     public boolean isEmpty() {
665 jsr166 1.2 return size == 0;
666 jsr166 1.1 }
667    
668     /**
669     * Returns an iterator over the elements in this deque. The elements
670     * will be ordered from first (head) to last (tail). This is the same
671     * order that elements would be dequeued (via successive calls to
672     * {@link #remove} or popped (via successive calls to {@link #pop}).
673     *
674     * @return an iterator over the elements in this deque
675     */
676     public Iterator<E> iterator() {
677     return new DeqIterator();
678     }
679    
680     public Iterator<E> descendingIterator() {
681     return new DescendingIterator();
682     }
683    
684     private class DeqIterator implements Iterator<E> {
685 jsr166 1.2 /** Index of element to be returned by subsequent call to next. */
686     int cursor;
687 jsr166 1.1
688 jsr166 1.2 /** Number of elements yet to be returned. */
689     int remaining = size;
690 jsr166 1.1
691     /**
692     * Index of element returned by most recent call to next.
693     * Reset to -1 if element is deleted by a call to remove.
694     */
695 jsr166 1.2 int lastRet = -1;
696    
697     DeqIterator() { cursor = head; }
698 jsr166 1.1
699 jsr166 1.2 public final boolean hasNext() {
700     return remaining > 0;
701 jsr166 1.1 }
702    
703     public E next() {
704 jsr166 1.2 if (remaining == 0)
705 jsr166 1.1 throw new NoSuchElementException();
706 jsr166 1.2 final Object[] elements = ArrayDeque.this.elements;
707     E e = checkedElementAt(elements, cursor);
708 jsr166 1.1 lastRet = cursor;
709 jsr166 1.2 if (++cursor >= elements.length) cursor = 0;
710     remaining--;
711     return e;
712     }
713    
714     void postDelete(boolean leftShifted) {
715     if (leftShifted)
716     if (--cursor < 0) cursor = elements.length - 1;
717 jsr166 1.1 }
718    
719 jsr166 1.2 public final void remove() {
720 jsr166 1.1 if (lastRet < 0)
721     throw new IllegalStateException();
722 jsr166 1.2 postDelete(delete(lastRet));
723     lastRet = -1;
724     }
725    
726     public void forEachRemaining(Consumer<? super E> action) {
727     int k;
728     if ((k = remaining) > 0) {
729     remaining = 0;
730     ArrayDeque.forEachRemaining(action, elements, cursor, k);
731     if ((lastRet = cursor + k - 1) >= elements.length)
732     lastRet -= elements.length;
733     }
734     }
735     }
736    
737     private class DescendingIterator extends DeqIterator {
738     DescendingIterator() { cursor = tail(); }
739    
740     public final E next() {
741     if (remaining == 0)
742     throw new NoSuchElementException();
743     final Object[] elements = ArrayDeque.this.elements;
744     E e = checkedElementAt(elements, cursor);
745     lastRet = cursor;
746     if (--cursor < 0) cursor = elements.length - 1;
747     remaining--;
748     return e;
749     }
750    
751     void postDelete(boolean leftShifted) {
752     if (!leftShifted)
753     if (++cursor >= elements.length) cursor = 0;
754     }
755    
756     public final void forEachRemaining(Consumer<? super E> action) {
757     int k;
758     if ((k = remaining) > 0) {
759     remaining = 0;
760     forEachRemainingDescending(action, elements, cursor, k);
761     if ((lastRet = cursor - (k - 1)) < 0)
762     lastRet += elements.length;
763     }
764     }
765     }
766    
767     /**
768     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
769     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
770     * deque.
771     *
772     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
773     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
774     * {@link Spliterator#NONNULL}. Overriding implementations should document
775     * the reporting of additional characteristic values.
776     *
777     * @return a {@code Spliterator} over the elements in this deque
778     * @since 1.8
779     */
780     public Spliterator<E> spliterator() {
781     return new ArrayDequeSpliterator();
782     }
783    
784     final class ArrayDequeSpliterator implements Spliterator<E> {
785     private int cursor;
786     private int remaining; // -1 until late-binding first use
787    
788     /** Constructs late-binding spliterator over all elements. */
789     ArrayDequeSpliterator() {
790     this.remaining = -1;
791     }
792    
793     /** Constructs spliterator over the given slice. */
794     ArrayDequeSpliterator(int cursor, int count) {
795     this.cursor = cursor;
796     this.remaining = count;
797     }
798    
799     /** Ensures late-binding initialization; then returns remaining. */
800     private int remaining() {
801     if (remaining < 0) {
802     cursor = head;
803     remaining = size;
804     }
805     return remaining;
806     }
807    
808     public ArrayDequeSpliterator trySplit() {
809     final int mid;
810     if ((mid = remaining() >> 1) > 0) {
811     int oldCursor = cursor;
812     cursor = add(cursor, mid, elements.length);
813     remaining -= mid;
814     return new ArrayDequeSpliterator(oldCursor, mid);
815 jsr166 1.1 }
816 jsr166 1.2 return null;
817 jsr166 1.1 }
818    
819     public void forEachRemaining(Consumer<? super E> action) {
820 jsr166 1.2 int k = remaining(); // side effect!
821     remaining = 0;
822     ArrayDeque.forEachRemaining(action, elements, cursor, k);
823     }
824    
825     public boolean tryAdvance(Consumer<? super E> action) {
826 jsr166 1.1 Objects.requireNonNull(action);
827 jsr166 1.2 if (remaining() == 0)
828     return false;
829     action.accept(checkedElementAt(elements, cursor));
830     if (++cursor >= elements.length) cursor = 0;
831     remaining--;
832     return true;
833     }
834    
835     public long estimateSize() {
836     return remaining();
837     }
838    
839     public int characteristics() {
840     return Spliterator.NONNULL
841     | Spliterator.ORDERED
842     | Spliterator.SIZED
843     | Spliterator.SUBSIZED;
844     }
845     }
846    
847     @SuppressWarnings("unchecked")
848     public void forEach(Consumer<? super E> action) {
849     Objects.requireNonNull(action);
850     final Object[] elements = this.elements;
851     final int capacity = elements.length;
852     int from, end, to, leftover;
853     leftover = (end = (from = head) + size)
854     - (to = (capacity - end >= 0) ? end : capacity);
855     for (;; from = 0, to = leftover, leftover = 0) {
856     for (int i = from; i < to; i++)
857     action.accept((E) elements[i]);
858     if (leftover == 0) break;
859     }
860     // checkInvariants();
861     }
862    
863     /**
864     * A variant of forEach that also checks for concurrent
865     * modification, for use in iterators.
866     */
867     static <E> void forEachRemaining(
868     Consumer<? super E> action, Object[] elements, int from, int size) {
869     Objects.requireNonNull(action);
870     final int capacity = elements.length;
871     int end, to, leftover;
872     leftover = (end = from + size)
873     - (to = (capacity - end >= 0) ? end : capacity);
874     for (;; from = 0, to = leftover, leftover = 0) {
875     for (int i = from; i < to; i++) {
876     @SuppressWarnings("unchecked") E e = (E) elements[i];
877     if (e == null)
878     throw new ConcurrentModificationException();
879     action.accept(e);
880     }
881     if (leftover == 0) break;
882     }
883     }
884    
885     static <E> void forEachRemainingDescending(
886     Consumer<? super E> action, Object[] elements, int from, int size) {
887     Objects.requireNonNull(action);
888     final int capacity = elements.length;
889     int end, to, leftover;
890     leftover = (to = ((end = from - size) >= -1) ? end : -1) - end;
891     for (;; from = capacity - 1, to = capacity - 1 - leftover, leftover = 0) {
892     for (int i = from; i > to; i--) {
893     @SuppressWarnings("unchecked") E e = (E) elements[i];
894 jsr166 1.1 if (e == null)
895     throw new ConcurrentModificationException();
896     action.accept(e);
897     }
898 jsr166 1.2 if (leftover == 0) break;
899     }
900     }
901    
902     /**
903     * Replaces each element of this deque with the result of applying the
904     * operator to that element, as specified by {@link List#replaceAll}.
905     *
906     * @param operator the operator to apply to each element
907     * @since TBD
908     */
909     /* public */ void replaceAll(UnaryOperator<E> operator) {
910     Objects.requireNonNull(operator);
911     final Object[] elements = this.elements;
912     final int capacity = elements.length;
913     int from, end, to, leftover;
914     leftover = (end = (from = head) + size)
915     - (to = (capacity - end >= 0) ? end : capacity);
916     for (;; from = 0, to = leftover, leftover = 0) {
917     for (int i = from; i < to; i++)
918     elements[i] = operator.apply(elementAt(i));
919     if (leftover == 0) break;
920 jsr166 1.1 }
921 jsr166 1.2 // checkInvariants();
922 jsr166 1.1 }
923    
924     /**
925 jsr166 1.2 * @throws NullPointerException {@inheritDoc}
926     */
927     public boolean removeIf(Predicate<? super E> filter) {
928     Objects.requireNonNull(filter);
929     return bulkRemove(filter);
930     }
931 jsr166 1.1
932 jsr166 1.2 /**
933     * @throws NullPointerException {@inheritDoc}
934     */
935     public boolean removeAll(Collection<?> c) {
936     Objects.requireNonNull(c);
937     return bulkRemove(e -> c.contains(e));
938     }
939 jsr166 1.1
940 jsr166 1.2 /**
941     * @throws NullPointerException {@inheritDoc}
942     */
943     public boolean retainAll(Collection<?> c) {
944     Objects.requireNonNull(c);
945     return bulkRemove(e -> !c.contains(e));
946     }
947 jsr166 1.1
948 jsr166 1.2 /** Implementation of bulk remove methods. */
949     private boolean bulkRemove(Predicate<? super E> filter) {
950     // checkInvariants();
951     final Object[] elements = this.elements;
952     final int capacity = elements.length;
953     int i = head, j = i, remaining = size, deleted = 0;
954     try {
955     for (; remaining > 0; remaining--) {
956     @SuppressWarnings("unchecked") E e = (E) elements[i];
957     if (filter.test(e))
958     deleted++;
959     else {
960     if (j != i)
961     elements[j] = e;
962     if (++j >= capacity) j = 0;
963     }
964     if (++i >= capacity) i = 0;
965 jsr166 1.1 }
966 jsr166 1.2 return deleted > 0;
967     } catch (Throwable ex) {
968     if (deleted > 0)
969     for (; remaining > 0; remaining--) {
970     elements[j] = elements[i];
971     if (++i >= capacity) i = 0;
972     if (++j >= capacity) j = 0;
973     }
974     throw ex;
975     } finally {
976     size -= deleted;
977     clearSlice(elements, j, deleted);
978     // checkInvariants();
979 jsr166 1.1 }
980     }
981    
982     /**
983     * Returns {@code true} if this deque contains the specified element.
984     * More formally, returns {@code true} if and only if this deque contains
985     * at least one element {@code e} such that {@code o.equals(e)}.
986     *
987     * @param o object to be checked for containment in this deque
988     * @return {@code true} if this deque contains the specified element
989     */
990     public boolean contains(Object o) {
991     if (o != null) {
992 jsr166 1.2 final Object[] elements = this.elements;
993     final int capacity = elements.length;
994     int from, end, to, leftover;
995     leftover = (end = (from = head) + size)
996     - (to = (capacity - end >= 0) ? end : capacity);
997     for (;; from = 0, to = leftover, leftover = 0) {
998     for (int i = from; i < to; i++)
999     if (o.equals(elements[i]))
1000     return true;
1001     if (leftover == 0) break;
1002 jsr166 1.1 }
1003     }
1004     return false;
1005     }
1006    
1007     /**
1008     * Removes a single instance of the specified element from this deque.
1009     * If the deque does not contain the element, it is unchanged.
1010     * More formally, removes the first element {@code e} such that
1011     * {@code o.equals(e)} (if such an element exists).
1012     * Returns {@code true} if this deque contained the specified element
1013     * (or equivalently, if this deque changed as a result of the call).
1014     *
1015     * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
1016     *
1017     * @param o element to be removed from this deque, if present
1018     * @return {@code true} if this deque contained the specified element
1019     */
1020     public boolean remove(Object o) {
1021     return removeFirstOccurrence(o);
1022     }
1023    
1024     /**
1025     * Removes all of the elements from this deque.
1026     * The deque will be empty after this call returns.
1027     */
1028     public void clear() {
1029 jsr166 1.2 clearSlice(elements, head, size);
1030     size = head = 0;
1031     // checkInvariants();
1032     }
1033    
1034     /**
1035     * Nulls out size elements, starting at head.
1036     */
1037     private static void clearSlice(Object[] elements, int head, int size) {
1038     final int capacity = elements.length, end = head + size;
1039     final int leg = (capacity - end >= 0) ? end : capacity;
1040     Arrays.fill(elements, head, leg, null);
1041     if (leg != end)
1042     Arrays.fill(elements, 0, end - capacity, null);
1043 jsr166 1.1 }
1044    
1045     /**
1046     * Returns an array containing all of the elements in this deque
1047     * in proper sequence (from first to last element).
1048     *
1049     * <p>The returned array will be "safe" in that no references to it are
1050     * maintained by this deque. (In other words, this method must allocate
1051     * a new array). The caller is thus free to modify the returned array.
1052     *
1053     * <p>This method acts as bridge between array-based and collection-based
1054     * APIs.
1055     *
1056     * @return an array containing all of the elements in this deque
1057     */
1058     public Object[] toArray() {
1059 jsr166 1.2 return toArray(Object[].class);
1060     }
1061    
1062     private <T> T[] toArray(Class<T[]> klazz) {
1063     final Object[] elements = this.elements;
1064     final int capacity = elements.length;
1065     final int head = this.head, end = head + size;
1066     final T[] a;
1067     if (end >= 0) {
1068     a = Arrays.copyOfRange(elements, head, end, klazz);
1069     } else {
1070     // integer overflow!
1071     a = Arrays.copyOfRange(elements, 0, size, klazz);
1072     System.arraycopy(elements, head, a, 0, capacity - head);
1073     }
1074     if (end - capacity > 0)
1075     System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1076 jsr166 1.1 return a;
1077     }
1078    
1079     /**
1080     * Returns an array containing all of the elements in this deque in
1081     * proper sequence (from first to last element); the runtime type of the
1082     * returned array is that of the specified array. If the deque fits in
1083     * the specified array, it is returned therein. Otherwise, a new array
1084     * is allocated with the runtime type of the specified array and the
1085     * size of this deque.
1086     *
1087     * <p>If this deque fits in the specified array with room to spare
1088     * (i.e., the array has more elements than this deque), the element in
1089     * the array immediately following the end of the deque is set to
1090     * {@code null}.
1091     *
1092     * <p>Like the {@link #toArray()} method, this method acts as bridge between
1093     * array-based and collection-based APIs. Further, this method allows
1094     * precise control over the runtime type of the output array, and may,
1095     * under certain circumstances, be used to save allocation costs.
1096     *
1097     * <p>Suppose {@code x} is a deque known to contain only strings.
1098     * The following code can be used to dump the deque into a newly
1099     * allocated array of {@code String}:
1100     *
1101     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1102     *
1103     * Note that {@code toArray(new Object[0])} is identical in function to
1104     * {@code toArray()}.
1105     *
1106     * @param a the array into which the elements of the deque are to
1107     * be stored, if it is big enough; otherwise, a new array of the
1108     * same runtime type is allocated for this purpose
1109     * @return an array containing all of the elements in this deque
1110     * @throws ArrayStoreException if the runtime type of the specified array
1111     * is not a supertype of the runtime type of every element in
1112     * this deque
1113     * @throws NullPointerException if the specified array is null
1114     */
1115     @SuppressWarnings("unchecked")
1116     public <T> T[] toArray(T[] a) {
1117 jsr166 1.2 final int size = this.size;
1118     if (size > a.length)
1119     return toArray((Class<T[]>) a.getClass());
1120     final Object[] elements = this.elements;
1121     final int capacity = elements.length;
1122     final int head = this.head, end = head + size;
1123     final int front = (capacity - end >= 0) ? size : capacity - head;
1124     System.arraycopy(elements, head, a, 0, front);
1125     if (front != size)
1126     System.arraycopy(elements, 0, a, capacity - head, end - capacity);
1127     if (size < a.length)
1128     a[size] = null;
1129 jsr166 1.1 return a;
1130     }
1131    
1132     // *** Object methods ***
1133    
1134     /**
1135     * Returns a copy of this deque.
1136     *
1137     * @return a copy of this deque
1138     */
1139     public ArrayDeque<E> clone() {
1140     try {
1141     @SuppressWarnings("unchecked")
1142     ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
1143     result.elements = Arrays.copyOf(elements, elements.length);
1144     return result;
1145     } catch (CloneNotSupportedException e) {
1146     throw new AssertionError();
1147     }
1148     }
1149    
1150     private static final long serialVersionUID = 2340985798034038923L;
1151    
1152     /**
1153     * Saves this deque to a stream (that is, serializes it).
1154     *
1155     * @param s the stream
1156     * @throws java.io.IOException if an I/O error occurs
1157     * @serialData The current size ({@code int}) of the deque,
1158     * followed by all of its elements (each an object reference) in
1159     * first-to-last order.
1160     */
1161     private void writeObject(java.io.ObjectOutputStream s)
1162     throws java.io.IOException {
1163     s.defaultWriteObject();
1164    
1165     // Write out size
1166 jsr166 1.2 s.writeInt(size);
1167 jsr166 1.1
1168     // Write out elements in order.
1169 jsr166 1.2 final Object[] elements = this.elements;
1170     final int capacity = elements.length;
1171     int from, end, to, leftover;
1172     leftover = (end = (from = head) + size)
1173     - (to = (capacity - end >= 0) ? end : capacity);
1174     for (;; from = 0, to = leftover, leftover = 0) {
1175     for (int i = from; i < to; i++)
1176     s.writeObject(elements[i]);
1177     if (leftover == 0) break;
1178     }
1179 jsr166 1.1 }
1180    
1181     /**
1182     * Reconstitutes this deque from a stream (that is, deserializes it).
1183     * @param s the stream
1184     * @throws ClassNotFoundException if the class of a serialized object
1185     * could not be found
1186     * @throws java.io.IOException if an I/O error occurs
1187     */
1188     private void readObject(java.io.ObjectInputStream s)
1189     throws java.io.IOException, ClassNotFoundException {
1190     s.defaultReadObject();
1191    
1192     // Read in size and allocate array
1193 jsr166 1.2 elements = new Object[size = s.readInt()];
1194 jsr166 1.1
1195     // Read in all elements in the proper order.
1196     for (int i = 0; i < size; i++)
1197     elements[i] = s.readObject();
1198     }
1199    
1200 jsr166 1.2 /** debugging */
1201     void checkInvariants() {
1202     try {
1203     int capacity = elements.length;
1204     // assert size >= 0 && size <= capacity;
1205     // assert head >= 0;
1206     // assert capacity == 0 || head < capacity;
1207     // assert size == 0 || elements[head] != null;
1208     // assert size == 0 || elements[tail()] != null;
1209     // assert size == capacity || elements[dec(head, capacity)] == null;
1210     // assert size == capacity || elements[inc(tail(), capacity)] == null;
1211     } catch (Throwable t) {
1212     System.err.printf("head=%d size=%d capacity=%d%n",
1213     head, size, elements.length);
1214     System.err.printf("elements=%s%n",
1215     Arrays.toString(elements));
1216     throw t;
1217 jsr166 1.1 }
1218     }
1219    
1220     }