ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.45
Committed: Fri Feb 1 01:02:25 2013 UTC (11 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.44: +3 -3 lines
Log Message:
Use new java.util.function names

File Contents

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