ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.47
Committed: Sun Feb 17 23:36:16 2013 UTC (11 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.46: +45 -33 lines
Log Message:
Spliterator sync

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