ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.51
Committed: Wed Feb 20 12:39:06 2013 UTC (11 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.50: +11 -9 lines
Log Message:
sync javadoc

File Contents

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