ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.41
Committed: Wed Jan 16 15:06:10 2013 UTC (11 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.40: +158 -17 lines
Log Message:
lambda-lib support

File Contents

# User Rev Content
1 dl 1.1 /*
2 dl 1.41 * 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 it
5     * under the terms of the GNU General Public License version 2 only, as
6     * published by the Free Software Foundation. Oracle designates this
7     * particular file as subject to the "Classpath" exception as provided
8     * 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 WITHOUT
11     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12     * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13     * version 2 for more details (a copy is included in the LICENSE file that
14     * accompanied this code).
15     *
16     * You should have received a copy of the GNU General Public License version
17     * 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 USA
21     * or visit www.oracle.com if you need additional information or have any
22     * questions.
23     */
24    
25     /*
26     * This file is available under and governed by the GNU General Public
27     * License version 2 only, as published by the Free Software Foundation.
28     * However, the following notice accompanied the original version of this
29     * file:
30     *
31 dl 1.1 * Written by Josh Bloch of Google Inc. and released to the public domain,
32 jsr166 1.31 * as explained at http://creativecommons.org/publicdomain/zero/1.0/.
33 dl 1.1 */
34    
35     package java.util;
36 dl 1.41 import java.util.Spliterator;
37     import java.util.stream.Stream;
38     import java.util.stream.Streams;
39     import java.util.function.Block;
40 dl 1.1
41     /**
42     * Resizable-array implementation of the {@link Deque} interface. Array
43     * deques have no capacity restrictions; they grow as necessary to support
44     * usage. They are not thread-safe; in the absence of external
45     * synchronization, they do not support concurrent access by multiple threads.
46     * Null elements are prohibited. This class is likely to be faster than
47 dl 1.2 * {@link Stack} when used as a stack, and faster than {@link LinkedList}
48 dl 1.1 * when used as a queue.
49     *
50 dl 1.41 * <p>Most <tt>ArrayDeque</tt> operations run in amortized constant time.
51     * Exceptions include {@link #remove(Object) remove}, {@link
52     * #removeFirstOccurrence removeFirstOccurrence}, {@link #removeLastOccurrence
53     * removeLastOccurrence}, {@link #contains contains}, {@link #iterator
54     * iterator.remove()}, and the bulk operations, all of which run in linear
55     * time.
56     *
57     * <p>The iterators returned by this class's <tt>iterator</tt> method are
58     * <i>fail-fast</i>: If the deque is modified at any time after the iterator
59     * is created, in any way except through the iterator's own <tt>remove</tt>
60     * method, the iterator will generally throw a {@link
61 jsr166 1.7 * ConcurrentModificationException}. Thus, in the face of concurrent
62     * modification, the iterator fails quickly and cleanly, rather than risking
63     * arbitrary, non-deterministic behavior at an undetermined time in the
64     * future.
65 dl 1.1 *
66     * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
67     * as it is, generally speaking, impossible to make any hard guarantees in the
68     * presence of unsynchronized concurrent modification. Fail-fast iterators
69 dl 1.41 * throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
70 dl 1.1 * Therefore, it would be wrong to write a program that depended on this
71     * exception for its correctness: <i>the fail-fast behavior of iterators
72     * should be used only to detect bugs.</i>
73     *
74     * <p>This class and its iterator implement all of the
75 jsr166 1.9 * <em>optional</em> methods of the {@link Collection} and {@link
76     * Iterator} interfaces.
77     *
78     * <p>This class is a member of the
79 jsr166 1.29 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
80 jsr166 1.9 * Java Collections Framework</a>.
81 dl 1.1 *
82     * @author Josh Bloch and Doug Lea
83     * @since 1.6
84     * @param <E> the type of elements held in this collection
85     */
86     public class ArrayDeque<E> extends AbstractCollection<E>
87 jsr166 1.32 implements Deque<E>, Cloneable, java.io.Serializable
88 dl 1.1 {
89     /**
90 dl 1.4 * The array in which the elements of the deque are stored.
91 dl 1.1 * The capacity of the deque is the length of this array, which is
92     * always a power of two. The array is never allowed to become
93     * full, except transiently within an addX method where it is
94     * resized (see doubleCapacity) immediately upon becoming full,
95     * thus avoiding head and tail wrapping around to equal each
96     * other. We also guarantee that all array cells not holding
97     * deque elements are always null.
98     */
99 dl 1.41 transient Object[] elements; // non-private to simplify nested class access
100 dl 1.1
101     /**
102     * The index of the element at the head of the deque (which is the
103     * element that would be removed by remove() or pop()); or an
104     * arbitrary number equal to tail if the deque is empty.
105     */
106 dl 1.41 transient int head;
107 dl 1.1
108     /**
109     * The index at which the next element would be added to the tail
110     * of the deque (via addLast(E), add(E), or push(E)).
111     */
112 dl 1.41 transient int tail;
113 dl 1.1
114     /**
115     * The minimum capacity that we'll use for a newly created deque.
116     * Must be a power of 2.
117     */
118     private static final int MIN_INITIAL_CAPACITY = 8;
119    
120     // ****** Array allocation and resizing utilities ******
121    
122     /**
123 jsr166 1.39 * Allocates empty array to hold the given number of elements.
124 dl 1.1 *
125 jsr166 1.9 * @param numElements the number of elements to hold
126 dl 1.1 */
127 dl 1.5 private void allocateElements(int numElements) {
128 dl 1.1 int initialCapacity = MIN_INITIAL_CAPACITY;
129     // Find the best power of two to hold elements.
130     // Tests "<=" because arrays aren't kept full.
131     if (numElements >= initialCapacity) {
132     initialCapacity = numElements;
133     initialCapacity |= (initialCapacity >>> 1);
134     initialCapacity |= (initialCapacity >>> 2);
135     initialCapacity |= (initialCapacity >>> 4);
136     initialCapacity |= (initialCapacity >>> 8);
137     initialCapacity |= (initialCapacity >>> 16);
138     initialCapacity++;
139    
140     if (initialCapacity < 0) // Too many elements, must back off
141     initialCapacity >>>= 1;// Good luck allocating 2 ^ 30 elements
142     }
143 jsr166 1.34 elements = new Object[initialCapacity];
144 dl 1.1 }
145    
146     /**
147 jsr166 1.39 * Doubles the capacity of this deque. Call only when full, i.e.,
148 dl 1.1 * when head and tail have wrapped around to become equal.
149     */
150     private void doubleCapacity() {
151 dl 1.5 assert head == tail;
152 dl 1.1 int p = head;
153     int n = elements.length;
154     int r = n - p; // number of elements to the right of p
155     int newCapacity = n << 1;
156     if (newCapacity < 0)
157     throw new IllegalStateException("Sorry, deque too big");
158     Object[] a = new Object[newCapacity];
159     System.arraycopy(elements, p, a, 0, r);
160     System.arraycopy(elements, 0, a, r, p);
161 jsr166 1.34 elements = a;
162 dl 1.1 head = 0;
163     tail = n;
164     }
165    
166     /**
167 jsr166 1.7 * Copies the elements from our element array into the specified array,
168 dl 1.1 * in order (from first to last element in the deque). It is assumed
169     * that the array is large enough to hold all elements in the deque.
170     *
171     * @return its argument
172     */
173     private <T> T[] copyElements(T[] a) {
174     if (head < tail) {
175     System.arraycopy(elements, head, a, 0, size());
176     } else if (head > tail) {
177     int headPortionLen = elements.length - head;
178     System.arraycopy(elements, head, a, 0, headPortionLen);
179     System.arraycopy(elements, 0, a, headPortionLen, tail);
180     }
181     return a;
182     }
183    
184     /**
185 dl 1.4 * Constructs an empty array deque with an initial capacity
186 dl 1.1 * sufficient to hold 16 elements.
187     */
188     public ArrayDeque() {
189 jsr166 1.34 elements = new Object[16];
190 dl 1.1 }
191    
192     /**
193     * Constructs an empty array deque with an initial capacity
194     * sufficient to hold the specified number of elements.
195     *
196     * @param numElements lower bound on initial capacity of the deque
197     */
198     public ArrayDeque(int numElements) {
199     allocateElements(numElements);
200     }
201    
202     /**
203     * Constructs a deque containing the elements of the specified
204     * collection, in the order they are returned by the collection's
205     * iterator. (The first element returned by the collection's
206     * iterator becomes the first element, or <i>front</i> of the
207     * deque.)
208     *
209     * @param c the collection whose elements are to be placed into the deque
210     * @throws NullPointerException if the specified collection is null
211     */
212     public ArrayDeque(Collection<? extends E> c) {
213     allocateElements(c.size());
214     addAll(c);
215     }
216    
217     // The main insertion and extraction methods are addFirst,
218     // addLast, pollFirst, pollLast. The other methods are defined in
219     // terms of these.
220    
221     /**
222 dl 1.5 * Inserts the specified element at the front of this deque.
223 dl 1.1 *
224 jsr166 1.9 * @param e the element to add
225     * @throws NullPointerException if the specified element is null
226 dl 1.1 */
227     public void addFirst(E e) {
228     if (e == null)
229     throw new NullPointerException();
230     elements[head = (head - 1) & (elements.length - 1)] = e;
231 dl 1.5 if (head == tail)
232 dl 1.1 doubleCapacity();
233     }
234    
235     /**
236 dl 1.6 * Inserts the specified element at the end of this deque.
237 jsr166 1.14 *
238     * <p>This method is equivalent to {@link #add}.
239 dl 1.1 *
240 jsr166 1.9 * @param e the element to add
241     * @throws NullPointerException if the specified element is null
242 dl 1.1 */
243     public void addLast(E e) {
244     if (e == null)
245     throw new NullPointerException();
246     elements[tail] = e;
247     if ( (tail = (tail + 1) & (elements.length - 1)) == head)
248     doubleCapacity();
249     }
250    
251     /**
252 dl 1.5 * Inserts the specified element at the front of this deque.
253 dl 1.1 *
254 jsr166 1.9 * @param e the element to add
255 jsr166 1.40 * @return {@code true} (as specified by {@link Deque#offerFirst})
256 jsr166 1.9 * @throws NullPointerException if the specified element is null
257 dl 1.1 */
258     public boolean offerFirst(E e) {
259     addFirst(e);
260     return true;
261     }
262    
263     /**
264 dl 1.6 * Inserts the specified element at the end of this deque.
265 dl 1.1 *
266 jsr166 1.9 * @param e the element to add
267 jsr166 1.40 * @return {@code true} (as specified by {@link Deque#offerLast})
268 jsr166 1.9 * @throws NullPointerException if the specified element is null
269 dl 1.1 */
270     public boolean offerLast(E e) {
271     addLast(e);
272     return true;
273     }
274    
275     /**
276 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
277 dl 1.1 */
278     public E removeFirst() {
279     E x = pollFirst();
280     if (x == null)
281     throw new NoSuchElementException();
282     return x;
283     }
284    
285     /**
286 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
287 dl 1.1 */
288     public E removeLast() {
289     E x = pollLast();
290     if (x == null)
291     throw new NoSuchElementException();
292     return x;
293     }
294    
295 jsr166 1.9 public E pollFirst() {
296     int h = head;
297 jsr166 1.37 @SuppressWarnings("unchecked")
298     E result = (E) elements[h];
299 jsr166 1.34 // Element is null if deque empty
300 jsr166 1.9 if (result == null)
301     return null;
302     elements[h] = null; // Must null out slot
303     head = (h + 1) & (elements.length - 1);
304     return result;
305 dl 1.1 }
306    
307 jsr166 1.9 public E pollLast() {
308     int t = (tail - 1) & (elements.length - 1);
309 jsr166 1.37 @SuppressWarnings("unchecked")
310     E result = (E) elements[t];
311 jsr166 1.9 if (result == null)
312     return null;
313     elements[t] = null;
314     tail = t;
315     return result;
316 dl 1.1 }
317    
318     /**
319 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
320 dl 1.1 */
321     public E getFirst() {
322 jsr166 1.37 @SuppressWarnings("unchecked")
323     E result = (E) elements[head];
324 jsr166 1.34 if (result == null)
325 dl 1.1 throw new NoSuchElementException();
326 jsr166 1.34 return result;
327 dl 1.1 }
328    
329     /**
330 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
331 dl 1.1 */
332     public E getLast() {
333 jsr166 1.34 @SuppressWarnings("unchecked")
334     E result = (E) elements[(tail - 1) & (elements.length - 1)];
335     if (result == null)
336 dl 1.1 throw new NoSuchElementException();
337 jsr166 1.34 return result;
338 dl 1.1 }
339    
340 jsr166 1.35 @SuppressWarnings("unchecked")
341 jsr166 1.9 public E peekFirst() {
342 jsr166 1.34 // elements[head] is null if deque empty
343 jsr166 1.35 return (E) elements[head];
344 jsr166 1.9 }
345    
346 jsr166 1.35 @SuppressWarnings("unchecked")
347 jsr166 1.9 public E peekLast() {
348 jsr166 1.35 return (E) elements[(tail - 1) & (elements.length - 1)];
349 jsr166 1.9 }
350    
351 dl 1.1 /**
352     * Removes the first occurrence of the specified element in this
353 jsr166 1.9 * deque (when traversing the deque from head to tail).
354     * If the deque does not contain the element, it is unchanged.
355 jsr166 1.40 * More formally, removes the first element {@code e} such that
356     * {@code o.equals(e)} (if such an element exists).
357     * Returns {@code true} if this deque contained the specified element
358 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
359 dl 1.1 *
360 dl 1.5 * @param o element to be removed from this deque, if present
361 jsr166 1.40 * @return {@code true} if the deque contained the specified element
362 dl 1.1 */
363 dl 1.5 public boolean removeFirstOccurrence(Object o) {
364     if (o == null)
365 dl 1.1 return false;
366     int mask = elements.length - 1;
367     int i = head;
368 jsr166 1.34 Object x;
369 dl 1.1 while ( (x = elements[i]) != null) {
370 dl 1.5 if (o.equals(x)) {
371 dl 1.1 delete(i);
372     return true;
373     }
374     i = (i + 1) & mask;
375     }
376     return false;
377     }
378    
379     /**
380     * Removes the last occurrence of the specified element in this
381 jsr166 1.9 * deque (when traversing the deque from head to tail).
382     * If the deque does not contain the element, it is unchanged.
383 jsr166 1.40 * More formally, removes the last element {@code e} such that
384     * {@code o.equals(e)} (if such an element exists).
385     * Returns {@code true} if this deque contained the specified element
386 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
387 dl 1.1 *
388 dl 1.5 * @param o element to be removed from this deque, if present
389 jsr166 1.40 * @return {@code true} if the deque contained the specified element
390 dl 1.1 */
391 dl 1.5 public boolean removeLastOccurrence(Object o) {
392     if (o == null)
393 dl 1.1 return false;
394     int mask = elements.length - 1;
395     int i = (tail - 1) & mask;
396 jsr166 1.34 Object x;
397 dl 1.1 while ( (x = elements[i]) != null) {
398 dl 1.5 if (o.equals(x)) {
399 dl 1.1 delete(i);
400     return true;
401     }
402     i = (i - 1) & mask;
403     }
404     return false;
405     }
406    
407     // *** Queue methods ***
408    
409     /**
410 dl 1.6 * Inserts the specified element at the end of this deque.
411 dl 1.1 *
412     * <p>This method is equivalent to {@link #addLast}.
413     *
414 jsr166 1.9 * @param e the element to add
415 jsr166 1.40 * @return {@code true} (as specified by {@link Collection#add})
416 jsr166 1.9 * @throws NullPointerException if the specified element is null
417 dl 1.1 */
418     public boolean add(E e) {
419     addLast(e);
420     return true;
421     }
422    
423     /**
424 jsr166 1.9 * Inserts the specified element at the end of this deque.
425 dl 1.1 *
426 jsr166 1.9 * <p>This method is equivalent to {@link #offerLast}.
427 dl 1.1 *
428 jsr166 1.9 * @param e the element to add
429 jsr166 1.40 * @return {@code true} (as specified by {@link Queue#offer})
430 jsr166 1.9 * @throws NullPointerException if the specified element is null
431 dl 1.1 */
432 jsr166 1.9 public boolean offer(E e) {
433     return offerLast(e);
434 dl 1.1 }
435    
436     /**
437     * Retrieves and removes the head of the queue represented by this deque.
438 jsr166 1.15 *
439     * This method differs from {@link #poll poll} only in that it throws an
440 jsr166 1.9 * exception if this deque is empty.
441 dl 1.1 *
442     * <p>This method is equivalent to {@link #removeFirst}.
443     *
444     * @return the head of the queue represented by this deque
445 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
446 dl 1.1 */
447     public E remove() {
448     return removeFirst();
449     }
450    
451     /**
452 jsr166 1.9 * Retrieves and removes the head of the queue represented by this deque
453     * (in other words, the first element of this deque), or returns
454 jsr166 1.40 * {@code null} if this deque is empty.
455 dl 1.1 *
456 jsr166 1.9 * <p>This method is equivalent to {@link #pollFirst}.
457 dl 1.1 *
458     * @return the head of the queue represented by this deque, or
459 jsr166 1.40 * {@code null} if this deque is empty
460 dl 1.1 */
461 jsr166 1.9 public E poll() {
462     return pollFirst();
463 dl 1.1 }
464    
465     /**
466     * Retrieves, but does not remove, the head of the queue represented by
467 jsr166 1.15 * this deque. This method differs from {@link #peek peek} only in
468     * that it throws an exception if this deque is empty.
469 dl 1.1 *
470 jsr166 1.8 * <p>This method is equivalent to {@link #getFirst}.
471 dl 1.1 *
472     * @return the head of the queue represented by this deque
473 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
474 dl 1.1 */
475     public E element() {
476     return getFirst();
477     }
478    
479 jsr166 1.9 /**
480     * Retrieves, but does not remove, the head of the queue represented by
481 jsr166 1.40 * this deque, or returns {@code null} if this deque is empty.
482 jsr166 1.9 *
483     * <p>This method is equivalent to {@link #peekFirst}.
484     *
485     * @return the head of the queue represented by this deque, or
486 jsr166 1.40 * {@code null} if this deque is empty
487 jsr166 1.9 */
488     public E peek() {
489     return peekFirst();
490     }
491    
492 dl 1.1 // *** Stack methods ***
493    
494     /**
495     * Pushes an element onto the stack represented by this deque. In other
496 dl 1.5 * words, inserts the element at the front of this deque.
497 dl 1.1 *
498     * <p>This method is equivalent to {@link #addFirst}.
499     *
500     * @param e the element to push
501 jsr166 1.9 * @throws NullPointerException if the specified element is null
502 dl 1.1 */
503     public void push(E e) {
504     addFirst(e);
505     }
506    
507     /**
508     * Pops an element from the stack represented by this deque. In other
509 dl 1.2 * words, removes and returns the first element of this deque.
510 dl 1.1 *
511     * <p>This method is equivalent to {@link #removeFirst()}.
512     *
513     * @return the element at the front of this deque (which is the top
514 jsr166 1.9 * of the stack represented by this deque)
515     * @throws NoSuchElementException {@inheritDoc}
516 dl 1.1 */
517     public E pop() {
518     return removeFirst();
519     }
520    
521 jsr166 1.25 private void checkInvariants() {
522 jsr166 1.30 assert elements[tail] == null;
523     assert head == tail ? elements[head] == null :
524     (elements[head] != null &&
525     elements[(tail - 1) & (elements.length - 1)] != null);
526     assert elements[(head - 1) & (elements.length - 1)] == null;
527 jsr166 1.25 }
528    
529 dl 1.1 /**
530 jsr166 1.7 * Removes the element at the specified position in the elements array,
531 jsr166 1.9 * adjusting head and tail as necessary. This can result in motion of
532     * elements backwards or forwards in the array.
533 dl 1.1 *
534 dl 1.5 * <p>This method is called delete rather than remove to emphasize
535 jsr166 1.9 * that its semantics differ from those of {@link List#remove(int)}.
536 dl 1.5 *
537 dl 1.1 * @return true if elements moved backwards
538     */
539     private boolean delete(int i) {
540 jsr166 1.30 checkInvariants();
541 jsr166 1.34 final Object[] elements = this.elements;
542 jsr166 1.30 final int mask = elements.length - 1;
543     final int h = head;
544     final int t = tail;
545     final int front = (i - h) & mask;
546     final int back = (t - i) & mask;
547    
548     // Invariant: head <= i < tail mod circularity
549     if (front >= ((t - h) & mask))
550     throw new ConcurrentModificationException();
551    
552     // Optimize for least element motion
553     if (front < back) {
554     if (h <= i) {
555     System.arraycopy(elements, h, elements, h + 1, front);
556     } else { // Wrap around
557     System.arraycopy(elements, 0, elements, 1, i);
558     elements[0] = elements[mask];
559     System.arraycopy(elements, h, elements, h + 1, mask - h);
560     }
561     elements[h] = null;
562     head = (h + 1) & mask;
563     return false;
564     } else {
565     if (i < t) { // Copy the null tail as well
566     System.arraycopy(elements, i + 1, elements, i, back);
567     tail = t - 1;
568     } else { // Wrap around
569     System.arraycopy(elements, i + 1, elements, i, mask - i);
570     elements[mask] = elements[0];
571     System.arraycopy(elements, 1, elements, 0, t);
572     tail = (t - 1) & mask;
573     }
574     return true;
575     }
576 dl 1.23 }
577    
578 dl 1.1 // *** Collection Methods ***
579    
580     /**
581     * Returns the number of elements in this deque.
582     *
583     * @return the number of elements in this deque
584     */
585     public int size() {
586     return (tail - head) & (elements.length - 1);
587     }
588    
589     /**
590 jsr166 1.40 * Returns {@code true} if this deque contains no elements.
591 dl 1.1 *
592 jsr166 1.40 * @return {@code true} if this deque contains no elements
593 dl 1.1 */
594     public boolean isEmpty() {
595     return head == tail;
596     }
597    
598     /**
599     * Returns an iterator over the elements in this deque. The elements
600     * will be ordered from first (head) to last (tail). This is the same
601     * order that elements would be dequeued (via successive calls to
602     * {@link #remove} or popped (via successive calls to {@link #pop}).
603 dl 1.5 *
604 jsr166 1.18 * @return an iterator over the elements in this deque
605 dl 1.1 */
606     public Iterator<E> iterator() {
607     return new DeqIterator();
608     }
609    
610 dl 1.16 public Iterator<E> descendingIterator() {
611     return new DescendingIterator();
612     }
613    
614 dl 1.1 private class DeqIterator implements Iterator<E> {
615     /**
616     * Index of element to be returned by subsequent call to next.
617     */
618     private int cursor = head;
619    
620     /**
621     * Tail recorded at construction (also in remove), to stop
622     * iterator and also to check for comodification.
623     */
624     private int fence = tail;
625    
626     /**
627     * Index of element returned by most recent call to next.
628     * Reset to -1 if element is deleted by a call to remove.
629     */
630     private int lastRet = -1;
631    
632     public boolean hasNext() {
633     return cursor != fence;
634     }
635    
636     public E next() {
637     if (cursor == fence)
638     throw new NoSuchElementException();
639 jsr166 1.37 @SuppressWarnings("unchecked")
640     E result = (E) elements[cursor];
641 dl 1.1 // This check doesn't catch all possible comodifications,
642     // but does catch the ones that corrupt traversal
643 jsr166 1.26 if (tail != fence || result == null)
644 dl 1.1 throw new ConcurrentModificationException();
645     lastRet = cursor;
646     cursor = (cursor + 1) & (elements.length - 1);
647     return result;
648     }
649    
650     public void remove() {
651     if (lastRet < 0)
652     throw new IllegalStateException();
653 jsr166 1.26 if (delete(lastRet)) { // if left-shifted, undo increment in next()
654 dl 1.17 cursor = (cursor - 1) & (elements.length - 1);
655 jsr166 1.30 fence = tail;
656     }
657 dl 1.1 lastRet = -1;
658     }
659     }
660    
661 dl 1.16 private class DescendingIterator implements Iterator<E> {
662 jsr166 1.18 /*
663 dl 1.17 * This class is nearly a mirror-image of DeqIterator, using
664 jsr166 1.26 * tail instead of head for initial cursor, and head instead of
665     * tail for fence.
666 dl 1.16 */
667 jsr166 1.26 private int cursor = tail;
668     private int fence = head;
669     private int lastRet = -1;
670 dl 1.16
671     public boolean hasNext() {
672     return cursor != fence;
673     }
674    
675     public E next() {
676     if (cursor == fence)
677     throw new NoSuchElementException();
678 jsr166 1.26 cursor = (cursor - 1) & (elements.length - 1);
679 jsr166 1.37 @SuppressWarnings("unchecked")
680     E result = (E) elements[cursor];
681 jsr166 1.26 if (head != fence || result == null)
682 dl 1.16 throw new ConcurrentModificationException();
683     lastRet = cursor;
684     return result;
685     }
686    
687     public void remove() {
688 jsr166 1.26 if (lastRet < 0)
689 dl 1.16 throw new IllegalStateException();
690 jsr166 1.26 if (!delete(lastRet)) {
691 dl 1.17 cursor = (cursor + 1) & (elements.length - 1);
692 jsr166 1.30 fence = head;
693     }
694 jsr166 1.26 lastRet = -1;
695 dl 1.16 }
696     }
697    
698 dl 1.1 /**
699 jsr166 1.40 * Returns {@code true} if this deque contains the specified element.
700     * More formally, returns {@code true} if and only if this deque contains
701     * at least one element {@code e} such that {@code o.equals(e)}.
702 dl 1.1 *
703     * @param o object to be checked for containment in this deque
704 jsr166 1.40 * @return {@code true} if this deque contains the specified element
705 dl 1.1 */
706     public boolean contains(Object o) {
707     if (o == null)
708     return false;
709     int mask = elements.length - 1;
710     int i = head;
711 jsr166 1.34 Object x;
712 dl 1.1 while ( (x = elements[i]) != null) {
713     if (o.equals(x))
714     return true;
715     i = (i + 1) & mask;
716     }
717     return false;
718     }
719    
720     /**
721     * Removes a single instance of the specified element from this deque.
722 jsr166 1.9 * If the deque does not contain the element, it is unchanged.
723 jsr166 1.40 * More formally, removes the first element {@code e} such that
724     * {@code o.equals(e)} (if such an element exists).
725     * Returns {@code true} if this deque contained the specified element
726 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
727 jsr166 1.9 *
728     * <p>This method is equivalent to {@link #removeFirstOccurrence}.
729 dl 1.1 *
730 jsr166 1.9 * @param o element to be removed from this deque, if present
731 jsr166 1.40 * @return {@code true} if this deque contained the specified element
732 dl 1.1 */
733 jsr166 1.9 public boolean remove(Object o) {
734     return removeFirstOccurrence(o);
735 dl 1.1 }
736    
737     /**
738     * Removes all of the elements from this deque.
739 jsr166 1.7 * The deque will be empty after this call returns.
740 dl 1.1 */
741     public void clear() {
742     int h = head;
743     int t = tail;
744     if (h != t) { // clear all cells
745     head = tail = 0;
746     int i = h;
747     int mask = elements.length - 1;
748     do {
749     elements[i] = null;
750     i = (i + 1) & mask;
751 jsr166 1.9 } while (i != t);
752 dl 1.1 }
753     }
754    
755     /**
756 dl 1.5 * Returns an array containing all of the elements in this deque
757 jsr166 1.10 * in proper sequence (from first to last element).
758 dl 1.1 *
759 jsr166 1.10 * <p>The returned array will be "safe" in that no references to it are
760     * maintained by this deque. (In other words, this method must allocate
761     * a new array). The caller is thus free to modify the returned array.
762 jsr166 1.13 *
763 jsr166 1.11 * <p>This method acts as bridge between array-based and collection-based
764     * APIs.
765     *
766 dl 1.5 * @return an array containing all of the elements in this deque
767 dl 1.1 */
768     public Object[] toArray() {
769 jsr166 1.30 return copyElements(new Object[size()]);
770 dl 1.1 }
771    
772     /**
773 jsr166 1.10 * Returns an array containing all of the elements in this deque in
774     * proper sequence (from first to last element); the runtime type of the
775     * returned array is that of the specified array. If the deque fits in
776     * the specified array, it is returned therein. Otherwise, a new array
777     * is allocated with the runtime type of the specified array and the
778     * size of this deque.
779     *
780     * <p>If this deque fits in the specified array with room to spare
781     * (i.e., the array has more elements than this deque), the element in
782     * the array immediately following the end of the deque is set to
783 jsr166 1.40 * {@code null}.
784 jsr166 1.10 *
785     * <p>Like the {@link #toArray()} method, this method acts as bridge between
786     * array-based and collection-based APIs. Further, this method allows
787     * precise control over the runtime type of the output array, and may,
788     * under certain circumstances, be used to save allocation costs.
789     *
790 jsr166 1.40 * <p>Suppose {@code x} is a deque known to contain only strings.
791 jsr166 1.10 * The following code can be used to dump the deque into a newly
792 jsr166 1.40 * allocated array of {@code String}:
793 jsr166 1.10 *
794 jsr166 1.33 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
795 jsr166 1.10 *
796 jsr166 1.40 * Note that {@code toArray(new Object[0])} is identical in function to
797     * {@code toArray()}.
798 dl 1.1 *
799     * @param a the array into which the elements of the deque are to
800 jsr166 1.9 * be stored, if it is big enough; otherwise, a new array of the
801     * same runtime type is allocated for this purpose
802 jsr166 1.10 * @return an array containing all of the elements in this deque
803     * @throws ArrayStoreException if the runtime type of the specified array
804     * is not a supertype of the runtime type of every element in
805     * this deque
806     * @throws NullPointerException if the specified array is null
807 dl 1.1 */
808 jsr166 1.34 @SuppressWarnings("unchecked")
809 dl 1.1 public <T> T[] toArray(T[] a) {
810     int size = size();
811     if (a.length < size)
812     a = (T[])java.lang.reflect.Array.newInstance(
813     a.getClass().getComponentType(), size);
814 jsr166 1.30 copyElements(a);
815 dl 1.1 if (a.length > size)
816     a[size] = null;
817     return a;
818     }
819    
820     // *** Object methods ***
821    
822     /**
823     * Returns a copy of this deque.
824     *
825     * @return a copy of this deque
826     */
827     public ArrayDeque<E> clone() {
828 dl 1.5 try {
829 jsr166 1.34 @SuppressWarnings("unchecked")
830 dl 1.1 ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
831 jsr166 1.28 result.elements = Arrays.copyOf(elements, elements.length);
832 dl 1.1 return result;
833 dl 1.5 } catch (CloneNotSupportedException e) {
834 dl 1.1 throw new AssertionError();
835     }
836     }
837    
838     private static final long serialVersionUID = 2340985798034038923L;
839    
840     /**
841 jsr166 1.38 * Saves this deque to a stream (that is, serializes it).
842 dl 1.1 *
843 jsr166 1.40 * @serialData The current size ({@code int}) of the deque,
844 dl 1.1 * followed by all of its elements (each an object reference) in
845     * first-to-last order.
846     */
847 jsr166 1.32 private void writeObject(java.io.ObjectOutputStream s)
848     throws java.io.IOException {
849 dl 1.1 s.defaultWriteObject();
850    
851     // Write out size
852 dl 1.19 s.writeInt(size());
853 dl 1.1
854     // Write out elements in order.
855     int mask = elements.length - 1;
856 dl 1.19 for (int i = head; i != tail; i = (i + 1) & mask)
857 dl 1.1 s.writeObject(elements[i]);
858     }
859    
860     /**
861 jsr166 1.38 * Reconstitutes this deque from a stream (that is, deserializes it).
862 dl 1.1 */
863 jsr166 1.32 private void readObject(java.io.ObjectInputStream s)
864     throws java.io.IOException, ClassNotFoundException {
865 dl 1.1 s.defaultReadObject();
866    
867     // Read in size and allocate array
868     int size = s.readInt();
869     allocateElements(size);
870     head = 0;
871     tail = size;
872    
873     // Read in all elements in the proper order.
874     for (int i = 0; i < size; i++)
875 jsr166 1.34 elements[i] = s.readObject();
876 dl 1.1 }
877 dl 1.41
878     public Stream<E> stream() {
879     int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_SIZED;
880     return Streams.stream
881     (() -> new DeqSpliterator<E>(this, head, tail), flags);
882     }
883     public Stream<E> parallelStream() {
884     int flags = Streams.STREAM_IS_ORDERED | Streams.STREAM_IS_SIZED;
885     return Streams.parallelStream
886     (() -> new DeqSpliterator<E>(this, head, tail), flags);
887     }
888    
889    
890     static final class DeqSpliterator<E> implements Spliterator<E>, Iterator<E> {
891     private final ArrayDeque<E> deq;
892     private final Object[] array;
893     private final int fence; // initially tail
894     private int index; // current index, modified on traverse/split
895    
896     /** Create new spliterator covering the given array and range */
897     DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
898     this.deq = deq; this.array = deq.elements;
899     this.index = origin; this.fence = fence;
900     }
901    
902     public DeqSpliterator<E> trySplit() {
903     int n = array.length;
904     int h = index, t = fence;
905     if (h != t && ((h + 1) & (n - 1)) != t) {
906     if (h > t)
907     t += n;
908     int m = ((h + t) >>> 1) & (n - 1);
909     return new DeqSpliterator<E>(deq, h, index = m);
910     }
911     return null;
912     }
913    
914     @SuppressWarnings("unchecked")
915     public void forEach(Block<? super E> block) {
916     if (block == null)
917     throw new NullPointerException();
918     Object[] a = array;
919     if (a != deq.elements)
920     throw new ConcurrentModificationException();
921     int m = a.length - 1, f = fence, i = index;
922     index = f;
923     while (i != f) {
924     Object e = a[i];
925     if (e == null)
926     throw new ConcurrentModificationException();
927     block.accept((E)e);
928     i = (i + 1) & m;
929     }
930     }
931    
932     @SuppressWarnings("unchecked")
933     public boolean tryAdvance(Block<? super E> block) {
934     if (block == null)
935     throw new NullPointerException();
936     Object[] a = array;
937     if (a != deq.elements)
938     throw new ConcurrentModificationException();
939     int m = a.length - 1, i = index;
940     if (i != fence) {
941     Object e = a[i];
942     if (e == null)
943     throw new ConcurrentModificationException();
944     block.accept((E)e);
945     index = (i + 1) & m;
946     return true;
947     }
948     return false;
949     }
950    
951     // Iterator support
952     public Iterator<E> iterator() {
953     return this;
954     }
955    
956     public boolean hasNext() {
957     return index >= 0 && index != fence;
958     }
959    
960     @SuppressWarnings("unchecked")
961     public E next() {
962     if (index < 0 || index == fence)
963     throw new NoSuchElementException();
964     Object[] a = array;
965     if (a != deq.elements)
966     throw new ConcurrentModificationException();
967     Object e = a[index];
968     if (e == null)
969     throw new ConcurrentModificationException();
970     index = (index + 1) & (a.length - 1);
971     return (E) e;
972     }
973    
974     public void remove() { throw new UnsupportedOperationException(); }
975    
976     // Other spliterator methods
977     public long estimateSize() {
978     int n = fence - index;
979     if (n < 0)
980     n += array.length;
981     return (long)n;
982     }
983     public boolean hasExactSize() { return true; }
984     public boolean hasExactSplits() { return true; }
985     }
986    
987 dl 1.1 }