ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.69
Committed: Fri Sep 18 02:06:44 2015 UTC (8 years, 8 months ago) by jsr166
Branch: MAIN
Changes since 1.68: +13 -0 lines
Log Message:
merge upstream changes

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 jsr166 1.66 final Object[] elements = this.elements;
251     final int h = head;
252 jsr166 1.37 @SuppressWarnings("unchecked")
253     E result = (E) elements[h];
254 jsr166 1.34 // Element is null if deque empty
255 jsr166 1.65 if (result != null) {
256     elements[h] = null; // Must null out slot
257     head = (h + 1) & (elements.length - 1);
258     }
259 jsr166 1.9 return result;
260 dl 1.1 }
261    
262 jsr166 1.9 public E pollLast() {
263 jsr166 1.66 final Object[] elements = this.elements;
264     final int t = (tail - 1) & (elements.length - 1);
265 jsr166 1.37 @SuppressWarnings("unchecked")
266     E result = (E) elements[t];
267 jsr166 1.65 if (result != null) {
268     elements[t] = null;
269     tail = t;
270     }
271 jsr166 1.9 return result;
272 dl 1.1 }
273    
274     /**
275 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
276 dl 1.1 */
277     public E getFirst() {
278 jsr166 1.37 @SuppressWarnings("unchecked")
279     E result = (E) elements[head];
280 jsr166 1.34 if (result == null)
281 dl 1.1 throw new NoSuchElementException();
282 jsr166 1.34 return result;
283 dl 1.1 }
284    
285     /**
286 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
287 dl 1.1 */
288     public E getLast() {
289 jsr166 1.34 @SuppressWarnings("unchecked")
290     E result = (E) elements[(tail - 1) & (elements.length - 1)];
291     if (result == null)
292 dl 1.1 throw new NoSuchElementException();
293 jsr166 1.34 return result;
294 dl 1.1 }
295    
296 jsr166 1.35 @SuppressWarnings("unchecked")
297 jsr166 1.9 public E peekFirst() {
298 jsr166 1.34 // elements[head] is null if deque empty
299 jsr166 1.35 return (E) elements[head];
300 jsr166 1.9 }
301    
302 jsr166 1.35 @SuppressWarnings("unchecked")
303 jsr166 1.9 public E peekLast() {
304 jsr166 1.35 return (E) elements[(tail - 1) & (elements.length - 1)];
305 jsr166 1.9 }
306    
307 dl 1.1 /**
308     * Removes the first occurrence of the specified element in this
309 jsr166 1.9 * deque (when traversing the deque from head to tail).
310     * If the deque does not contain the element, it is unchanged.
311 jsr166 1.40 * More formally, removes the first element {@code e} such that
312     * {@code o.equals(e)} (if such an element exists).
313     * Returns {@code true} if this deque contained the specified element
314 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
315 dl 1.1 *
316 dl 1.5 * @param o element to be removed from this deque, if present
317 jsr166 1.40 * @return {@code true} if the deque contained the specified element
318 dl 1.1 */
319 dl 1.5 public boolean removeFirstOccurrence(Object o) {
320 jsr166 1.58 if (o != null) {
321     int mask = elements.length - 1;
322     int i = head;
323 jsr166 1.59 for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
324 jsr166 1.58 if (o.equals(x)) {
325     delete(i);
326     return true;
327     }
328 dl 1.1 }
329     }
330     return false;
331     }
332    
333     /**
334     * Removes the last occurrence of the specified element in this
335 jsr166 1.9 * deque (when traversing the deque from head to tail).
336     * If the deque does not contain the element, it is unchanged.
337 jsr166 1.40 * More formally, removes the last element {@code e} such that
338     * {@code o.equals(e)} (if such an element exists).
339     * Returns {@code true} if this deque contained the specified element
340 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
341 dl 1.1 *
342 dl 1.5 * @param o element to be removed from this deque, if present
343 jsr166 1.40 * @return {@code true} if the deque contained the specified element
344 dl 1.1 */
345 dl 1.5 public boolean removeLastOccurrence(Object o) {
346 jsr166 1.59 if (o != null) {
347     int mask = elements.length - 1;
348     int i = (tail - 1) & mask;
349     for (Object x; (x = elements[i]) != null; i = (i - 1) & mask) {
350     if (o.equals(x)) {
351     delete(i);
352     return true;
353     }
354 dl 1.1 }
355     }
356     return false;
357     }
358    
359     // *** Queue methods ***
360    
361     /**
362 dl 1.6 * Inserts the specified element at the end of this deque.
363 dl 1.1 *
364     * <p>This method is equivalent to {@link #addLast}.
365     *
366 jsr166 1.9 * @param e the element to add
367 jsr166 1.40 * @return {@code true} (as specified by {@link Collection#add})
368 jsr166 1.9 * @throws NullPointerException if the specified element is null
369 dl 1.1 */
370     public boolean add(E e) {
371     addLast(e);
372     return true;
373     }
374    
375     /**
376 jsr166 1.9 * Inserts the specified element at the end of this deque.
377 dl 1.1 *
378 jsr166 1.9 * <p>This method is equivalent to {@link #offerLast}.
379 dl 1.1 *
380 jsr166 1.9 * @param e the element to add
381 jsr166 1.40 * @return {@code true} (as specified by {@link Queue#offer})
382 jsr166 1.9 * @throws NullPointerException if the specified element is null
383 dl 1.1 */
384 jsr166 1.9 public boolean offer(E e) {
385     return offerLast(e);
386 dl 1.1 }
387    
388     /**
389     * Retrieves and removes the head of the queue represented by this deque.
390 jsr166 1.15 *
391     * This method differs from {@link #poll poll} only in that it throws an
392 jsr166 1.9 * exception if this deque is empty.
393 dl 1.1 *
394     * <p>This method is equivalent to {@link #removeFirst}.
395     *
396     * @return the head of the queue represented by this deque
397 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
398 dl 1.1 */
399     public E remove() {
400     return removeFirst();
401     }
402    
403     /**
404 jsr166 1.9 * Retrieves and removes the head of the queue represented by this deque
405     * (in other words, the first element of this deque), or returns
406 jsr166 1.40 * {@code null} if this deque is empty.
407 dl 1.1 *
408 jsr166 1.9 * <p>This method is equivalent to {@link #pollFirst}.
409 dl 1.1 *
410     * @return the head of the queue represented by this deque, or
411 jsr166 1.40 * {@code null} if this deque is empty
412 dl 1.1 */
413 jsr166 1.9 public E poll() {
414     return pollFirst();
415 dl 1.1 }
416    
417     /**
418     * Retrieves, but does not remove, the head of the queue represented by
419 jsr166 1.15 * this deque. This method differs from {@link #peek peek} only in
420     * that it throws an exception if this deque is empty.
421 dl 1.1 *
422 jsr166 1.8 * <p>This method is equivalent to {@link #getFirst}.
423 dl 1.1 *
424     * @return the head of the queue represented by this deque
425 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
426 dl 1.1 */
427     public E element() {
428     return getFirst();
429     }
430    
431 jsr166 1.9 /**
432     * Retrieves, but does not remove, the head of the queue represented by
433 jsr166 1.40 * this deque, or returns {@code null} if this deque is empty.
434 jsr166 1.9 *
435     * <p>This method is equivalent to {@link #peekFirst}.
436     *
437     * @return the head of the queue represented by this deque, or
438 jsr166 1.40 * {@code null} if this deque is empty
439 jsr166 1.9 */
440     public E peek() {
441     return peekFirst();
442     }
443    
444 dl 1.1 // *** Stack methods ***
445    
446     /**
447     * Pushes an element onto the stack represented by this deque. In other
448 dl 1.5 * words, inserts the element at the front of this deque.
449 dl 1.1 *
450     * <p>This method is equivalent to {@link #addFirst}.
451     *
452     * @param e the element to push
453 jsr166 1.9 * @throws NullPointerException if the specified element is null
454 dl 1.1 */
455     public void push(E e) {
456     addFirst(e);
457     }
458    
459     /**
460     * Pops an element from the stack represented by this deque. In other
461 dl 1.2 * words, removes and returns the first element of this deque.
462 dl 1.1 *
463     * <p>This method is equivalent to {@link #removeFirst()}.
464     *
465     * @return the element at the front of this deque (which is the top
466 jsr166 1.9 * of the stack represented by this deque)
467     * @throws NoSuchElementException {@inheritDoc}
468 dl 1.1 */
469     public E pop() {
470     return removeFirst();
471     }
472    
473 jsr166 1.25 private void checkInvariants() {
474 jsr166 1.30 assert elements[tail] == null;
475     assert head == tail ? elements[head] == null :
476     (elements[head] != null &&
477     elements[(tail - 1) & (elements.length - 1)] != null);
478     assert elements[(head - 1) & (elements.length - 1)] == null;
479 jsr166 1.25 }
480    
481 dl 1.1 /**
482 jsr166 1.7 * Removes the element at the specified position in the elements array,
483 jsr166 1.9 * adjusting head and tail as necessary. This can result in motion of
484     * elements backwards or forwards in the array.
485 dl 1.1 *
486 dl 1.5 * <p>This method is called delete rather than remove to emphasize
487 jsr166 1.9 * that its semantics differ from those of {@link List#remove(int)}.
488 dl 1.5 *
489 dl 1.1 * @return true if elements moved backwards
490     */
491     private boolean delete(int i) {
492 jsr166 1.30 checkInvariants();
493 jsr166 1.34 final Object[] elements = this.elements;
494 jsr166 1.30 final int mask = elements.length - 1;
495     final int h = head;
496     final int t = tail;
497     final int front = (i - h) & mask;
498     final int back = (t - i) & mask;
499    
500     // Invariant: head <= i < tail mod circularity
501     if (front >= ((t - h) & mask))
502     throw new ConcurrentModificationException();
503    
504     // Optimize for least element motion
505     if (front < back) {
506     if (h <= i) {
507     System.arraycopy(elements, h, elements, h + 1, front);
508     } else { // Wrap around
509     System.arraycopy(elements, 0, elements, 1, i);
510     elements[0] = elements[mask];
511     System.arraycopy(elements, h, elements, h + 1, mask - h);
512     }
513     elements[h] = null;
514     head = (h + 1) & mask;
515     return false;
516     } else {
517     if (i < t) { // Copy the null tail as well
518     System.arraycopy(elements, i + 1, elements, i, back);
519     tail = t - 1;
520     } else { // Wrap around
521     System.arraycopy(elements, i + 1, elements, i, mask - i);
522     elements[mask] = elements[0];
523     System.arraycopy(elements, 1, elements, 0, t);
524     tail = (t - 1) & mask;
525     }
526     return true;
527     }
528 dl 1.23 }
529    
530 dl 1.1 // *** Collection Methods ***
531    
532     /**
533     * Returns the number of elements in this deque.
534     *
535     * @return the number of elements in this deque
536     */
537     public int size() {
538     return (tail - head) & (elements.length - 1);
539     }
540    
541     /**
542 jsr166 1.40 * Returns {@code true} if this deque contains no elements.
543 dl 1.1 *
544 jsr166 1.40 * @return {@code true} if this deque contains no elements
545 dl 1.1 */
546     public boolean isEmpty() {
547     return head == tail;
548     }
549    
550     /**
551     * Returns an iterator over the elements in this deque. The elements
552     * will be ordered from first (head) to last (tail). This is the same
553     * order that elements would be dequeued (via successive calls to
554     * {@link #remove} or popped (via successive calls to {@link #pop}).
555 dl 1.5 *
556 jsr166 1.18 * @return an iterator over the elements in this deque
557 dl 1.1 */
558     public Iterator<E> iterator() {
559     return new DeqIterator();
560     }
561    
562 dl 1.16 public Iterator<E> descendingIterator() {
563     return new DescendingIterator();
564     }
565    
566 dl 1.1 private class DeqIterator implements Iterator<E> {
567     /**
568     * Index of element to be returned by subsequent call to next.
569     */
570     private int cursor = head;
571    
572     /**
573     * Tail recorded at construction (also in remove), to stop
574     * iterator and also to check for comodification.
575     */
576     private int fence = tail;
577    
578     /**
579     * Index of element returned by most recent call to next.
580     * Reset to -1 if element is deleted by a call to remove.
581     */
582     private int lastRet = -1;
583    
584     public boolean hasNext() {
585     return cursor != fence;
586     }
587    
588     public E next() {
589     if (cursor == fence)
590     throw new NoSuchElementException();
591 jsr166 1.37 @SuppressWarnings("unchecked")
592     E result = (E) elements[cursor];
593 dl 1.1 // This check doesn't catch all possible comodifications,
594     // but does catch the ones that corrupt traversal
595 jsr166 1.26 if (tail != fence || result == null)
596 dl 1.1 throw new ConcurrentModificationException();
597     lastRet = cursor;
598     cursor = (cursor + 1) & (elements.length - 1);
599     return result;
600     }
601    
602     public void remove() {
603     if (lastRet < 0)
604     throw new IllegalStateException();
605 jsr166 1.26 if (delete(lastRet)) { // if left-shifted, undo increment in next()
606 dl 1.17 cursor = (cursor - 1) & (elements.length - 1);
607 jsr166 1.30 fence = tail;
608     }
609 dl 1.1 lastRet = -1;
610     }
611 jsr166 1.68
612     public void forEachRemaining(Consumer<? super E> action) {
613     Objects.requireNonNull(action);
614     Object[] a = elements;
615     int m = a.length - 1, f = fence, i = cursor;
616     cursor = f;
617     while (i != f) {
618     @SuppressWarnings("unchecked") E e = (E)a[i];
619     i = (i + 1) & m;
620     if (e == null)
621     throw new ConcurrentModificationException();
622     action.accept(e);
623     }
624     }
625 dl 1.1 }
626    
627 jsr166 1.52 /**
628     * This class is nearly a mirror-image of DeqIterator, using tail
629     * instead of head for initial cursor, and head instead of tail
630     * for fence.
631     */
632 dl 1.16 private class DescendingIterator implements Iterator<E> {
633 jsr166 1.26 private int cursor = tail;
634     private int fence = head;
635     private int lastRet = -1;
636 dl 1.16
637     public boolean hasNext() {
638     return cursor != fence;
639     }
640    
641     public E next() {
642     if (cursor == fence)
643     throw new NoSuchElementException();
644 jsr166 1.26 cursor = (cursor - 1) & (elements.length - 1);
645 jsr166 1.37 @SuppressWarnings("unchecked")
646     E result = (E) elements[cursor];
647 jsr166 1.26 if (head != fence || result == null)
648 dl 1.16 throw new ConcurrentModificationException();
649     lastRet = cursor;
650     return result;
651     }
652    
653     public void remove() {
654 jsr166 1.26 if (lastRet < 0)
655 dl 1.16 throw new IllegalStateException();
656 jsr166 1.26 if (!delete(lastRet)) {
657 dl 1.17 cursor = (cursor + 1) & (elements.length - 1);
658 jsr166 1.30 fence = head;
659     }
660 jsr166 1.26 lastRet = -1;
661 dl 1.16 }
662     }
663    
664 dl 1.1 /**
665 jsr166 1.40 * Returns {@code true} if this deque contains the specified element.
666     * More formally, returns {@code true} if and only if this deque contains
667     * at least one element {@code e} such that {@code o.equals(e)}.
668 dl 1.1 *
669     * @param o object to be checked for containment in this deque
670 jsr166 1.40 * @return {@code true} if this deque contains the specified element
671 dl 1.1 */
672     public boolean contains(Object o) {
673 jsr166 1.58 if (o != null) {
674     int mask = elements.length - 1;
675     int i = head;
676 jsr166 1.59 for (Object x; (x = elements[i]) != null; i = (i + 1) & mask) {
677 jsr166 1.58 if (o.equals(x))
678     return true;
679     }
680 dl 1.1 }
681     return false;
682     }
683    
684     /**
685     * Removes a single instance of the specified element from this deque.
686 jsr166 1.9 * If the deque does not contain the element, it is unchanged.
687 jsr166 1.40 * More formally, removes the first element {@code e} such that
688     * {@code o.equals(e)} (if such an element exists).
689     * Returns {@code true} if this deque contained the specified element
690 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
691 jsr166 1.9 *
692 jsr166 1.46 * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
693 dl 1.1 *
694 jsr166 1.9 * @param o element to be removed from this deque, if present
695 jsr166 1.40 * @return {@code true} if this deque contained the specified element
696 dl 1.1 */
697 jsr166 1.9 public boolean remove(Object o) {
698     return removeFirstOccurrence(o);
699 dl 1.1 }
700    
701     /**
702     * Removes all of the elements from this deque.
703 jsr166 1.7 * The deque will be empty after this call returns.
704 dl 1.1 */
705     public void clear() {
706     int h = head;
707     int t = tail;
708     if (h != t) { // clear all cells
709     head = tail = 0;
710     int i = h;
711     int mask = elements.length - 1;
712     do {
713     elements[i] = null;
714     i = (i + 1) & mask;
715 jsr166 1.9 } while (i != t);
716 dl 1.1 }
717     }
718    
719     /**
720 dl 1.5 * Returns an array containing all of the elements in this deque
721 jsr166 1.10 * in proper sequence (from first to last element).
722 dl 1.1 *
723 jsr166 1.10 * <p>The returned array will be "safe" in that no references to it are
724     * maintained by this deque. (In other words, this method must allocate
725     * a new array). The caller is thus free to modify the returned array.
726 jsr166 1.13 *
727 jsr166 1.11 * <p>This method acts as bridge between array-based and collection-based
728     * APIs.
729     *
730 dl 1.5 * @return an array containing all of the elements in this deque
731 dl 1.1 */
732     public Object[] toArray() {
733 jsr166 1.50 final int head = this.head;
734     final int tail = this.tail;
735     boolean wrap = (tail < head);
736     int end = wrap ? tail + elements.length : tail;
737     Object[] a = Arrays.copyOfRange(elements, head, end);
738     if (wrap)
739     System.arraycopy(elements, 0, a, elements.length - head, tail);
740     return a;
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.63 * <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 jsr166 1.50 final int head = this.head;
782     final int tail = this.tail;
783     boolean wrap = (tail < head);
784     int size = (tail - head) + (wrap ? elements.length : 0);
785     int firstLeg = size - (wrap ? tail : 0);
786     int len = a.length;
787     if (size > len) {
788     a = (T[]) Arrays.copyOfRange(elements, head, head + size,
789     a.getClass());
790     } else {
791     System.arraycopy(elements, head, a, 0, firstLeg);
792     if (size < len)
793     a[size] = null;
794     }
795     if (wrap)
796     System.arraycopy(elements, 0, a, firstLeg, tail);
797 dl 1.1 return a;
798     }
799    
800     // *** Object methods ***
801    
802     /**
803     * Returns a copy of this deque.
804     *
805     * @return a copy of this deque
806     */
807     public ArrayDeque<E> clone() {
808 dl 1.5 try {
809 jsr166 1.34 @SuppressWarnings("unchecked")
810 dl 1.1 ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
811 jsr166 1.28 result.elements = Arrays.copyOf(elements, elements.length);
812 dl 1.1 return result;
813 dl 1.5 } catch (CloneNotSupportedException e) {
814 dl 1.1 throw new AssertionError();
815     }
816     }
817    
818     private static final long serialVersionUID = 2340985798034038923L;
819    
820     /**
821 jsr166 1.38 * Saves this deque to a stream (that is, serializes it).
822 dl 1.1 *
823 jsr166 1.56 * @param s the stream
824 jsr166 1.57 * @throws java.io.IOException if an I/O error occurs
825 jsr166 1.40 * @serialData The current size ({@code int}) of the deque,
826 dl 1.1 * followed by all of its elements (each an object reference) in
827     * first-to-last order.
828     */
829 jsr166 1.32 private void writeObject(java.io.ObjectOutputStream s)
830     throws java.io.IOException {
831 dl 1.1 s.defaultWriteObject();
832    
833     // Write out size
834 dl 1.19 s.writeInt(size());
835 dl 1.1
836     // Write out elements in order.
837     int mask = elements.length - 1;
838 dl 1.19 for (int i = head; i != tail; i = (i + 1) & mask)
839 dl 1.1 s.writeObject(elements[i]);
840     }
841    
842     /**
843 jsr166 1.38 * Reconstitutes this deque from a stream (that is, deserializes it).
844 jsr166 1.56 * @param s the stream
845 jsr166 1.57 * @throws ClassNotFoundException if the class of a serialized object
846     * could not be found
847     * @throws java.io.IOException if an I/O error occurs
848 dl 1.1 */
849 jsr166 1.32 private void readObject(java.io.ObjectInputStream s)
850     throws java.io.IOException, ClassNotFoundException {
851 dl 1.1 s.defaultReadObject();
852    
853     // Read in size and allocate array
854     int size = s.readInt();
855     allocateElements(size);
856     head = 0;
857     tail = size;
858    
859     // Read in all elements in the proper order.
860     for (int i = 0; i < size; i++)
861 jsr166 1.34 elements[i] = s.readObject();
862 dl 1.1 }
863 dl 1.41
864 jsr166 1.69 /**
865     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
866     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
867     * deque.
868     *
869     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
870     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
871     * {@link Spliterator#NONNULL}. Overriding implementations should document
872     * the reporting of additional characteristic values.
873     *
874     * @return a {@code Spliterator} over the elements in this deque
875     * @since 1.8
876     */
877 dl 1.53 public Spliterator<E> spliterator() {
878 jsr166 1.67 return new DeqSpliterator<>(this, -1, -1);
879 dl 1.47 }
880    
881 dl 1.44 static final class DeqSpliterator<E> implements Spliterator<E> {
882 dl 1.41 private final ArrayDeque<E> deq;
883 dl 1.47 private int fence; // -1 until first use
884     private int index; // current index, modified on traverse/split
885 jsr166 1.48
886 jsr166 1.49 /** Creates new spliterator covering the given array and range */
887 dl 1.41 DeqSpliterator(ArrayDeque<E> deq, int origin, int fence) {
888 dl 1.47 this.deq = deq;
889     this.index = origin;
890     this.fence = fence;
891     }
892    
893     private int getFence() { // force initialization
894     int t;
895     if ((t = fence) < 0) {
896     t = fence = deq.tail;
897     index = deq.head;
898     }
899     return t;
900 dl 1.41 }
901    
902 dl 1.53 public Spliterator<E> trySplit() {
903 dl 1.47 int t = getFence(), h = index, n = deq.elements.length;
904 dl 1.41 if (h != t && ((h + 1) & (n - 1)) != t) {
905     if (h > t)
906     t += n;
907     int m = ((h + t) >>> 1) & (n - 1);
908 dl 1.47 return new DeqSpliterator<>(deq, h, index = m);
909 dl 1.41 }
910     return null;
911     }
912    
913 dl 1.54 public void forEachRemaining(Consumer<? super E> consumer) {
914 dl 1.47 if (consumer == null)
915 dl 1.41 throw new NullPointerException();
916 dl 1.44 Object[] a = deq.elements;
917 dl 1.47 int m = a.length - 1, f = getFence(), i = index;
918 dl 1.41 index = f;
919     while (i != f) {
920 dl 1.44 @SuppressWarnings("unchecked") E e = (E)a[i];
921     i = (i + 1) & m;
922 dl 1.41 if (e == null)
923     throw new ConcurrentModificationException();
924 dl 1.47 consumer.accept(e);
925 dl 1.41 }
926     }
927    
928 dl 1.47 public boolean tryAdvance(Consumer<? super E> consumer) {
929     if (consumer == null)
930 dl 1.41 throw new NullPointerException();
931 dl 1.44 Object[] a = deq.elements;
932 dl 1.47 int m = a.length - 1, f = getFence(), i = index;
933 dl 1.64 if (i != f) {
934 dl 1.44 @SuppressWarnings("unchecked") E e = (E)a[i];
935     index = (i + 1) & m;
936 dl 1.41 if (e == null)
937     throw new ConcurrentModificationException();
938 dl 1.47 consumer.accept(e);
939 dl 1.41 return true;
940     }
941     return false;
942     }
943    
944 jsr166 1.42 public long estimateSize() {
945 dl 1.47 int n = getFence() - index;
946 dl 1.41 if (n < 0)
947 dl 1.44 n += deq.elements.length;
948 dl 1.47 return (long) n;
949     }
950    
951     @Override
952     public int characteristics() {
953 jsr166 1.48 return Spliterator.ORDERED | Spliterator.SIZED |
954 dl 1.47 Spliterator.NONNULL | Spliterator.SUBSIZED;
955 dl 1.41 }
956     }
957    
958 dl 1.1 }