ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.35
Committed: Fri Dec 2 15:47:22 2011 UTC (12 years, 5 months ago) by jsr166
Branch: MAIN
Changes since 1.34: +4 -5 lines
Log Message:
avoid introducing locals just for warning suppression

File Contents

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