ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.62
Committed: Wed Dec 31 09:37:19 2014 UTC (9 years, 4 months ago) by jsr166
Branch: MAIN
Changes since 1.61: +0 -1 lines
Log Message:
remove unused/redundant imports

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