ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.79
Committed: Tue Oct 18 20:32:55 2016 UTC (7 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.78: +24 -28 lines
Log Message:
no new public methods in jdk 9

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 jsr166 1.75 import java.util.function.Predicate;
11     import java.util.function.UnaryOperator;
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 jsr166 1.51 * Exceptions include
24     * {@link #remove(Object) remove},
25     * {@link #removeFirstOccurrence removeFirstOccurrence},
26     * {@link #removeLastOccurrence removeLastOccurrence},
27     * {@link #contains contains},
28     * {@link #iterator iterator.remove()},
29     * and the bulk operations, all of which run in linear time.
30 dl 1.41 *
31 jsr166 1.51 * <p>The iterators returned by this class's {@link #iterator() iterator}
32     * method are <em>fail-fast</em>: If the deque is modified at any time after
33     * the iterator is created, in any way except through the iterator's own
34     * {@code remove} method, the iterator will generally throw a {@link
35 jsr166 1.7 * ConcurrentModificationException}. Thus, in the face of concurrent
36     * modification, the iterator fails quickly and cleanly, rather than risking
37     * arbitrary, non-deterministic behavior at an undetermined time in the
38     * future.
39 dl 1.1 *
40     * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
41     * as it is, generally speaking, impossible to make any hard guarantees in the
42     * presence of unsynchronized concurrent modification. Fail-fast iterators
43 jsr166 1.43 * throw {@code ConcurrentModificationException} on a best-effort basis.
44 dl 1.1 * Therefore, it would be wrong to write a program that depended on this
45     * exception for its correctness: <i>the fail-fast behavior of iterators
46     * should be used only to detect bugs.</i>
47     *
48     * <p>This class and its iterator implement all of the
49 jsr166 1.9 * <em>optional</em> methods of the {@link Collection} and {@link
50     * Iterator} interfaces.
51     *
52     * <p>This class is a member of the
53 jsr166 1.29 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
54 jsr166 1.9 * Java Collections Framework</a>.
55 dl 1.1 *
56     * @author Josh Bloch and Doug Lea
57 jsr166 1.74 * @param <E> the type of elements held in this deque
58 dl 1.1 * @since 1.6
59     */
60     public class ArrayDeque<E> extends AbstractCollection<E>
61 dl 1.47 implements Deque<E>, Cloneable, Serializable
62 dl 1.1 {
63     /**
64 dl 1.4 * The array in which the elements of the deque are stored.
65 jsr166 1.75 * We guarantee that all array cells not holding deque elements
66     * are always null.
67 dl 1.1 */
68 jsr166 1.75 transient Object[] elements;
69 dl 1.1
70     /**
71     * The index of the element at the head of the deque (which is the
72     * element that would be removed by remove() or pop()); or an
73 jsr166 1.75 * arbitrary number 0 <= head < elements.length if the deque is empty.
74 dl 1.1 */
75 dl 1.41 transient int head;
76 dl 1.1
77 jsr166 1.75 /** Number of elements in this collection. */
78     transient int size;
79    
80 dl 1.1 /**
81 jsr166 1.75 * The maximum size of array to allocate.
82     * Some VMs reserve some header words in an array.
83     * Attempts to allocate larger arrays may result in
84     * OutOfMemoryError: Requested array size exceeds VM limit
85 dl 1.1 */
86 jsr166 1.75 private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
87 dl 1.1
88     /**
89 jsr166 1.75 * Increases the capacity of this deque by at least the given amount.
90     *
91     * @param needed the required minimum extra capacity; must be positive
92 dl 1.1 */
93 jsr166 1.75 private void grow(int needed) {
94     // overflow-conscious code
95     // checkInvariants();
96     int oldCapacity = elements.length;
97     int newCapacity;
98     // Double size if small; else grow by 50%
99     int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);
100     if (jump < needed
101     || (newCapacity = (oldCapacity + jump)) - MAX_ARRAY_SIZE > 0)
102     newCapacity = newCapacity(needed, jump);
103     elements = Arrays.copyOf(elements, newCapacity);
104     if (oldCapacity - head < size) {
105     // wrap around; slide first leg forward to end of array
106     int newSpace = newCapacity - oldCapacity;
107     System.arraycopy(elements, head,
108     elements, head + newSpace,
109     oldCapacity - head);
110     Arrays.fill(elements, head, head + newSpace, null);
111     head += newSpace;
112     }
113     // checkInvariants();
114     }
115 dl 1.1
116 jsr166 1.75 /** Capacity calculation for edge conditions, especially overflow. */
117     private int newCapacity(int needed, int jump) {
118     int oldCapacity = elements.length;
119     int minCapacity;
120     if ((minCapacity = oldCapacity + needed) - MAX_ARRAY_SIZE > 0) {
121     if (minCapacity < 0)
122     throw new IllegalStateException("Sorry, deque too big");
123     return Integer.MAX_VALUE;
124     }
125     if (needed > jump)
126     return minCapacity;
127     return (oldCapacity + jump - MAX_ARRAY_SIZE < 0)
128     ? oldCapacity + jump
129     : MAX_ARRAY_SIZE;
130     }
131 dl 1.1
132     /**
133 jsr166 1.75 * Increases the internal storage of this collection, if necessary,
134     * to ensure that it can hold at least the given number of elements.
135 dl 1.1 *
136 jsr166 1.75 * @param minCapacity the desired minimum capacity
137 dl 1.1 */
138 jsr166 1.79 /* TODO: public */ private void ensureCapacity(int minCapacity) {
139 jsr166 1.75 if (minCapacity > elements.length)
140     grow(minCapacity - elements.length);
141     // checkInvariants();
142 dl 1.1 }
143    
144     /**
145 jsr166 1.75 * Minimizes the internal storage of this collection.
146 dl 1.1 */
147 jsr166 1.79 /* TODO: public */ private void trimToSize() {
148 jsr166 1.75 if (size < elements.length) {
149     elements = toArray();
150     head = 0;
151     }
152     // checkInvariants();
153 dl 1.1 }
154    
155     /**
156 dl 1.4 * Constructs an empty array deque with an initial capacity
157 dl 1.1 * sufficient to hold 16 elements.
158     */
159     public ArrayDeque() {
160 jsr166 1.34 elements = new Object[16];
161 dl 1.1 }
162    
163     /**
164     * Constructs an empty array deque with an initial capacity
165     * sufficient to hold the specified number of elements.
166     *
167 jsr166 1.75 * @param numElements lower bound on initial capacity of the deque
168 dl 1.1 */
169     public ArrayDeque(int numElements) {
170 jsr166 1.75 elements = new Object[numElements];
171 dl 1.1 }
172    
173     /**
174     * Constructs a deque containing the elements of the specified
175     * collection, in the order they are returned by the collection's
176     * iterator. (The first element returned by the collection's
177     * iterator becomes the first element, or <i>front</i> of the
178     * deque.)
179     *
180     * @param c the collection whose elements are to be placed into the deque
181     * @throws NullPointerException if the specified collection is null
182     */
183     public ArrayDeque(Collection<? extends E> c) {
184 jsr166 1.75 Object[] elements = c.toArray();
185     // defend against c.toArray (incorrectly) not returning Object[]
186     // (see e.g. https://bugs.openjdk.java.net/browse/JDK-6260652)
187     if (elements.getClass() != Object[].class)
188     elements = Arrays.copyOf(elements, size, Object[].class);
189     for (Object obj : elements)
190     Objects.requireNonNull(obj);
191     size = elements.length;
192     this.elements = elements;
193     }
194    
195     /**
196 jsr166 1.79 * Increments i, mod modulus.
197     * Precondition and postcondition: 0 <= i < modulus.
198 jsr166 1.75 */
199 jsr166 1.79 static final int inc(int i, int modulus) {
200     if (++i == modulus) i = 0;
201     return i;
202 jsr166 1.75 }
203    
204     /**
205 jsr166 1.79 * Decrements i, mod modulus.
206     * Precondition and postcondition: 0 <= i < modulus.
207 jsr166 1.75 */
208 jsr166 1.79 static final int dec(int i, int modulus) {
209     if (--i < 0) i += modulus;
210 jsr166 1.75 return i;
211     }
212    
213     /**
214 jsr166 1.79 * Adds i and j, mod modulus.
215     * Precondition and postcondition: 0 <= i < modulus, 0 <= j <= modulus.
216 jsr166 1.75 */
217 jsr166 1.79 static final int add(int i, int j, int modulus) {
218     if ((i += j) - modulus >= 0) i -= modulus;
219 jsr166 1.75 return i;
220     }
221    
222     /**
223 jsr166 1.79 * Returns the array index of the last element.
224     * May return invalid index -1 if there are no elements.
225 jsr166 1.75 */
226 jsr166 1.79 final int tail() {
227     return add(head, size - 1, elements.length);
228 jsr166 1.75 }
229    
230     /**
231     * Returns element at array index i.
232     */
233     @SuppressWarnings("unchecked")
234     final E elementAt(int i) {
235     return (E) elements[i];
236     }
237    
238     /**
239     * A version of elementAt that checks for null elements.
240     * This check doesn't catch all possible comodifications,
241     * but does catch ones that corrupt traversal.
242     */
243     E checkedElementAt(Object[] elements, int i) {
244     @SuppressWarnings("unchecked") E e = (E) elements[i];
245     if (e == null)
246     throw new ConcurrentModificationException();
247     return e;
248 dl 1.1 }
249    
250     // The main insertion and extraction methods are addFirst,
251     // addLast, pollFirst, pollLast. The other methods are defined in
252     // terms of these.
253    
254     /**
255 dl 1.5 * Inserts the specified element at the front of this deque.
256 dl 1.1 *
257 jsr166 1.9 * @param e the element to add
258     * @throws NullPointerException if the specified element is null
259 dl 1.1 */
260     public void addFirst(E e) {
261 jsr166 1.75 // checkInvariants();
262     Objects.requireNonNull(e);
263     Object[] elements;
264     int capacity, s = size;
265     while (s == (capacity = (elements = this.elements).length))
266     grow(1);
267     elements[head = dec(head, capacity)] = e;
268     size = s + 1;
269 dl 1.1 }
270    
271     /**
272 dl 1.6 * Inserts the specified element at the end of this deque.
273 jsr166 1.14 *
274     * <p>This method is equivalent to {@link #add}.
275 dl 1.1 *
276 jsr166 1.9 * @param e the element to add
277     * @throws NullPointerException if the specified element is null
278 dl 1.1 */
279     public void addLast(E e) {
280 jsr166 1.75 // checkInvariants();
281     Objects.requireNonNull(e);
282     Object[] elements;
283     int capacity, s = size;
284     while (s == (capacity = (elements = this.elements).length))
285     grow(1);
286     elements[add(head, s, capacity)] = e;
287     size = s + 1;
288     }
289    
290     /**
291     * Adds all of the elements in the specified collection at the end
292     * of this deque, as if by calling {@link #addLast} on each one,
293     * in the order that they are returned by the collection's
294     * iterator.
295     *
296     * @param c the elements to be inserted into this deque
297     * @return {@code true} if this deque changed as a result of the call
298     * @throws NullPointerException if the specified collection or any
299     * of its elements are null
300     */
301     @Override
302     public boolean addAll(Collection<? extends E> c) {
303     // checkInvariants();
304     Object[] a, elements;
305 jsr166 1.79 int newcomers, capacity, s = size;
306     if ((newcomers = (a = c.toArray()).length) == 0)
307 jsr166 1.75 return false;
308 jsr166 1.79 while ((capacity = (elements = this.elements).length) - s < newcomers)
309     grow(newcomers - (capacity - s));
310 jsr166 1.75 int i = add(head, s, capacity);
311     for (Object x : a) {
312     Objects.requireNonNull(x);
313     elements[i] = x;
314     i = inc(i, capacity);
315     size++;
316     }
317     return true;
318 dl 1.1 }
319    
320     /**
321 dl 1.5 * Inserts the specified element at the front of this deque.
322 dl 1.1 *
323 jsr166 1.9 * @param e the element to add
324 jsr166 1.40 * @return {@code true} (as specified by {@link Deque#offerFirst})
325 jsr166 1.9 * @throws NullPointerException if the specified element is null
326 dl 1.1 */
327     public boolean offerFirst(E e) {
328     addFirst(e);
329     return true;
330     }
331    
332     /**
333 dl 1.6 * Inserts the specified element at the end of this deque.
334 dl 1.1 *
335 jsr166 1.9 * @param e the element to add
336 jsr166 1.40 * @return {@code true} (as specified by {@link Deque#offerLast})
337 jsr166 1.9 * @throws NullPointerException if the specified element is null
338 dl 1.1 */
339     public boolean offerLast(E e) {
340     addLast(e);
341     return true;
342     }
343    
344     /**
345 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
346 dl 1.1 */
347     public E removeFirst() {
348 jsr166 1.75 // checkInvariants();
349 dl 1.1 E x = pollFirst();
350     if (x == null)
351     throw new NoSuchElementException();
352     return x;
353     }
354    
355     /**
356 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
357 dl 1.1 */
358     public E removeLast() {
359 jsr166 1.75 // checkInvariants();
360 dl 1.1 E x = pollLast();
361     if (x == null)
362     throw new NoSuchElementException();
363     return x;
364     }
365    
366 jsr166 1.9 public E pollFirst() {
367 jsr166 1.75 // checkInvariants();
368     final int s, h;
369     if ((s = size) == 0)
370     return null;
371 jsr166 1.66 final Object[] elements = this.elements;
372 jsr166 1.75 @SuppressWarnings("unchecked") E e = (E) elements[h = head];
373     elements[h] = null;
374     head = inc(h, elements.length);
375     size = s - 1;
376     return e;
377 dl 1.1 }
378    
379 jsr166 1.9 public E pollLast() {
380 jsr166 1.75 // checkInvariants();
381     final int s, tail;
382     if ((s = size) == 0)
383     return null;
384 jsr166 1.66 final Object[] elements = this.elements;
385 jsr166 1.37 @SuppressWarnings("unchecked")
386 jsr166 1.75 E e = (E) elements[tail = add(head, s - 1, elements.length)];
387     elements[tail] = null;
388     size = s - 1;
389     return e;
390 dl 1.1 }
391    
392     /**
393 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
394 dl 1.1 */
395     public E getFirst() {
396 jsr166 1.75 // checkInvariants();
397     if (size == 0) throw new NoSuchElementException();
398     return elementAt(head);
399 dl 1.1 }
400    
401     /**
402 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
403 dl 1.1 */
404     public E getLast() {
405 jsr166 1.75 // checkInvariants();
406     if (size == 0) throw new NoSuchElementException();
407     return elementAt(tail());
408 dl 1.1 }
409    
410 jsr166 1.9 public E peekFirst() {
411 jsr166 1.75 // checkInvariants();
412     return (size == 0) ? null : elementAt(head);
413 jsr166 1.9 }
414    
415     public E peekLast() {
416 jsr166 1.75 // checkInvariants();
417     return (size == 0) ? null : elementAt(tail());
418 jsr166 1.9 }
419    
420 dl 1.1 /**
421     * Removes the first occurrence of the specified element in this
422 jsr166 1.9 * deque (when traversing the deque from head to tail).
423     * If the deque does not contain the element, it is unchanged.
424 jsr166 1.40 * More formally, removes the first element {@code e} such that
425     * {@code o.equals(e)} (if such an element exists).
426     * Returns {@code true} if this deque contained the specified element
427 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
428 dl 1.1 *
429 dl 1.5 * @param o element to be removed from this deque, if present
430 jsr166 1.40 * @return {@code true} if the deque contained the specified element
431 dl 1.1 */
432 dl 1.5 public boolean removeFirstOccurrence(Object o) {
433 jsr166 1.75 // checkInvariants();
434 jsr166 1.58 if (o != null) {
435 jsr166 1.75 final Object[] elements = this.elements;
436     final int capacity = elements.length;
437     for (int k = size, i = head; --k >= 0; i = inc(i, capacity)) {
438     if (o.equals(elements[i])) {
439 jsr166 1.58 delete(i);
440     return true;
441     }
442 dl 1.1 }
443     }
444     return false;
445     }
446    
447     /**
448     * Removes the last occurrence of the specified element in this
449 jsr166 1.9 * deque (when traversing the deque from head to tail).
450     * If the deque does not contain the element, it is unchanged.
451 jsr166 1.40 * More formally, removes the last element {@code e} such that
452     * {@code o.equals(e)} (if such an element exists).
453     * Returns {@code true} if this deque contained the specified element
454 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
455 dl 1.1 *
456 dl 1.5 * @param o element to be removed from this deque, if present
457 jsr166 1.40 * @return {@code true} if the deque contained the specified element
458 dl 1.1 */
459 dl 1.5 public boolean removeLastOccurrence(Object o) {
460 jsr166 1.59 if (o != null) {
461 jsr166 1.75 final Object[] elements = this.elements;
462     final int capacity = elements.length;
463     for (int k = size, i = add(head, k - 1, capacity);
464     --k >= 0; i = dec(i, capacity)) {
465     if (o.equals(elements[i])) {
466 jsr166 1.59 delete(i);
467     return true;
468     }
469 dl 1.1 }
470     }
471     return false;
472     }
473    
474     // *** Queue methods ***
475    
476     /**
477 dl 1.6 * Inserts the specified element at the end of this deque.
478 dl 1.1 *
479     * <p>This method is equivalent to {@link #addLast}.
480     *
481 jsr166 1.9 * @param e the element to add
482 jsr166 1.40 * @return {@code true} (as specified by {@link Collection#add})
483 jsr166 1.9 * @throws NullPointerException if the specified element is null
484 dl 1.1 */
485     public boolean add(E e) {
486     addLast(e);
487     return true;
488     }
489    
490     /**
491 jsr166 1.9 * Inserts the specified element at the end of this deque.
492 dl 1.1 *
493 jsr166 1.9 * <p>This method is equivalent to {@link #offerLast}.
494 dl 1.1 *
495 jsr166 1.9 * @param e the element to add
496 jsr166 1.40 * @return {@code true} (as specified by {@link Queue#offer})
497 jsr166 1.9 * @throws NullPointerException if the specified element is null
498 dl 1.1 */
499 jsr166 1.9 public boolean offer(E e) {
500     return offerLast(e);
501 dl 1.1 }
502    
503     /**
504     * Retrieves and removes the head of the queue represented by this deque.
505 jsr166 1.15 *
506     * This method differs from {@link #poll poll} only in that it throws an
507 jsr166 1.9 * exception if this deque is empty.
508 dl 1.1 *
509     * <p>This method is equivalent to {@link #removeFirst}.
510     *
511     * @return the head of the queue represented by this deque
512 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
513 dl 1.1 */
514     public E remove() {
515     return removeFirst();
516     }
517    
518     /**
519 jsr166 1.9 * Retrieves and removes the head of the queue represented by this deque
520     * (in other words, the first element of this deque), or returns
521 jsr166 1.40 * {@code null} if this deque is empty.
522 dl 1.1 *
523 jsr166 1.9 * <p>This method is equivalent to {@link #pollFirst}.
524 dl 1.1 *
525     * @return the head of the queue represented by this deque, or
526 jsr166 1.40 * {@code null} if this deque is empty
527 dl 1.1 */
528 jsr166 1.9 public E poll() {
529     return pollFirst();
530 dl 1.1 }
531    
532     /**
533     * Retrieves, but does not remove, the head of the queue represented by
534 jsr166 1.15 * this deque. This method differs from {@link #peek peek} only in
535     * that it throws an exception if this deque is empty.
536 dl 1.1 *
537 jsr166 1.8 * <p>This method is equivalent to {@link #getFirst}.
538 dl 1.1 *
539     * @return the head of the queue represented by this deque
540 jsr166 1.9 * @throws NoSuchElementException {@inheritDoc}
541 dl 1.1 */
542     public E element() {
543     return getFirst();
544     }
545    
546 jsr166 1.9 /**
547     * Retrieves, but does not remove, the head of the queue represented by
548 jsr166 1.40 * this deque, or returns {@code null} if this deque is empty.
549 jsr166 1.9 *
550     * <p>This method is equivalent to {@link #peekFirst}.
551     *
552     * @return the head of the queue represented by this deque, or
553 jsr166 1.40 * {@code null} if this deque is empty
554 jsr166 1.9 */
555     public E peek() {
556     return peekFirst();
557     }
558    
559 dl 1.1 // *** Stack methods ***
560    
561     /**
562     * Pushes an element onto the stack represented by this deque. In other
563 dl 1.5 * words, inserts the element at the front of this deque.
564 dl 1.1 *
565     * <p>This method is equivalent to {@link #addFirst}.
566     *
567     * @param e the element to push
568 jsr166 1.9 * @throws NullPointerException if the specified element is null
569 dl 1.1 */
570     public void push(E e) {
571     addFirst(e);
572     }
573    
574     /**
575     * Pops an element from the stack represented by this deque. In other
576 dl 1.2 * words, removes and returns the first element of this deque.
577 dl 1.1 *
578     * <p>This method is equivalent to {@link #removeFirst()}.
579     *
580     * @return the element at the front of this deque (which is the top
581 jsr166 1.9 * of the stack represented by this deque)
582     * @throws NoSuchElementException {@inheritDoc}
583 dl 1.1 */
584     public E pop() {
585     return removeFirst();
586     }
587    
588     /**
589 jsr166 1.75 * Removes the element at the specified position in the elements array.
590     * This can result in forward or backwards motion of array elements.
591     * We optimize for least element motion.
592 dl 1.1 *
593 dl 1.5 * <p>This method is called delete rather than remove to emphasize
594 jsr166 1.9 * that its semantics differ from those of {@link List#remove(int)}.
595 dl 1.5 *
596 dl 1.1 * @return true if elements moved backwards
597     */
598 jsr166 1.71 boolean delete(int i) {
599 jsr166 1.75 // checkInvariants();
600 jsr166 1.34 final Object[] elements = this.elements;
601 jsr166 1.75 final int capacity = elements.length;
602 jsr166 1.30 final int h = head;
603 jsr166 1.75 int front; // number of elements before to-be-deleted elt
604     if ((front = i - h) < 0) front += capacity;
605     final int back = size - front - 1; // number of elements after
606 jsr166 1.30 if (front < back) {
607 jsr166 1.75 // move front elements forwards
608 jsr166 1.30 if (h <= i) {
609     System.arraycopy(elements, h, elements, h + 1, front);
610     } else { // Wrap around
611     System.arraycopy(elements, 0, elements, 1, i);
612 jsr166 1.75 elements[0] = elements[capacity - 1];
613     System.arraycopy(elements, h, elements, h + 1, front - (i + 1));
614 jsr166 1.30 }
615     elements[h] = null;
616 jsr166 1.75 head = inc(h, capacity);
617     size--;
618     // checkInvariants();
619 jsr166 1.30 return false;
620     } else {
621 jsr166 1.75 // move back elements backwards
622     int tail = tail();
623     if (i <= tail) {
624 jsr166 1.30 System.arraycopy(elements, i + 1, elements, i, back);
625     } else { // Wrap around
626 jsr166 1.75 int firstLeg = capacity - (i + 1);
627     System.arraycopy(elements, i + 1, elements, i, firstLeg);
628     elements[capacity - 1] = elements[0];
629     System.arraycopy(elements, 1, elements, 0, back - firstLeg - 1);
630 jsr166 1.30 }
631 jsr166 1.75 elements[tail] = null;
632     size--;
633     // checkInvariants();
634 jsr166 1.30 return true;
635     }
636 dl 1.23 }
637    
638 dl 1.1 // *** Collection Methods ***
639    
640     /**
641     * Returns the number of elements in this deque.
642     *
643     * @return the number of elements in this deque
644     */
645     public int size() {
646 jsr166 1.75 return size;
647 dl 1.1 }
648    
649     /**
650 jsr166 1.40 * Returns {@code true} if this deque contains no elements.
651 dl 1.1 *
652 jsr166 1.40 * @return {@code true} if this deque contains no elements
653 dl 1.1 */
654     public boolean isEmpty() {
655 jsr166 1.75 return size == 0;
656 dl 1.1 }
657    
658     /**
659     * Returns an iterator over the elements in this deque. The elements
660     * will be ordered from first (head) to last (tail). This is the same
661     * order that elements would be dequeued (via successive calls to
662     * {@link #remove} or popped (via successive calls to {@link #pop}).
663 dl 1.5 *
664 jsr166 1.18 * @return an iterator over the elements in this deque
665 dl 1.1 */
666     public Iterator<E> iterator() {
667     return new DeqIterator();
668     }
669    
670 dl 1.16 public Iterator<E> descendingIterator() {
671     return new DescendingIterator();
672     }
673    
674 dl 1.1 private class DeqIterator implements Iterator<E> {
675 jsr166 1.75 /** Index of element to be returned by subsequent call to next. */
676     int cursor;
677 dl 1.1
678 jsr166 1.75 /** Number of elements yet to be returned. */
679     int remaining = size;
680 dl 1.1
681     /**
682     * Index of element returned by most recent call to next.
683     * Reset to -1 if element is deleted by a call to remove.
684     */
685 jsr166 1.75 int lastRet = -1;
686 dl 1.1
687 jsr166 1.75 DeqIterator() { cursor = head; }
688    
689 jsr166 1.77 int advance(int i, int modulus) {
690     return inc(i, modulus);
691 dl 1.1 }
692    
693 jsr166 1.75 void doRemove() {
694     if (delete(lastRet))
695     // if left-shifted, undo advance in next()
696     cursor = dec(cursor, elements.length);
697     }
698    
699     public final boolean hasNext() {
700     return remaining > 0;
701     }
702    
703     public final E next() {
704     if (remaining == 0)
705 dl 1.1 throw new NoSuchElementException();
706 jsr166 1.75 E e = checkedElementAt(elements, cursor);
707 dl 1.1 lastRet = cursor;
708 jsr166 1.77 cursor = advance(cursor, elements.length);
709 jsr166 1.75 remaining--;
710     return e;
711 dl 1.1 }
712    
713 jsr166 1.75 public final void remove() {
714 dl 1.1 if (lastRet < 0)
715     throw new IllegalStateException();
716 jsr166 1.75 doRemove();
717 dl 1.1 lastRet = -1;
718     }
719 jsr166 1.68
720 jsr166 1.75 public final void forEachRemaining(Consumer<? super E> action) {
721 jsr166 1.68 Objects.requireNonNull(action);
722 jsr166 1.75 final Object[] elements = ArrayDeque.this.elements;
723     final int capacity = elements.length;
724 jsr166 1.77 int k = remaining;
725     remaining = 0;
726     for (int i = cursor; --k >= 0; i = advance(i, capacity))
727     action.accept(checkedElementAt(elements, i));
728 jsr166 1.68 }
729 dl 1.1 }
730    
731 jsr166 1.75 private class DescendingIterator extends DeqIterator {
732     DescendingIterator() { cursor = tail(); }
733    
734 jsr166 1.77 @Override int advance(int i, int modulus) {
735     return dec(i, modulus);
736 jsr166 1.75 }
737    
738     @Override void doRemove() {
739     if (!delete(lastRet))
740     // if right-shifted, undo advance in next
741     cursor = inc(cursor, elements.length);
742     }
743     }
744    
745 jsr166 1.52 /**
746 jsr166 1.75 * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
747     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
748     * deque.
749     *
750     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
751     * {@link Spliterator#SUBSIZED}, {@link Spliterator#ORDERED}, and
752     * {@link Spliterator#NONNULL}. Overriding implementations should document
753     * the reporting of additional characteristic values.
754     *
755     * @return a {@code Spliterator} over the elements in this deque
756     * @since 1.8
757 jsr166 1.52 */
758 jsr166 1.75 public Spliterator<E> spliterator() {
759 jsr166 1.76 return new ArrayDequeSpliterator();
760 jsr166 1.75 }
761    
762     final class ArrayDequeSpliterator implements Spliterator<E> {
763     private int cursor;
764 jsr166 1.76 private int remaining; // -1 until late-binding first use
765 jsr166 1.75
766 jsr166 1.76 /** Constructs late-binding spliterator over all elements. */
767     ArrayDequeSpliterator() {
768     this.remaining = -1;
769     }
770    
771     /** Constructs spliterator over the given slice. */
772 jsr166 1.75 ArrayDequeSpliterator(int cursor, int count) {
773     this.cursor = cursor;
774     this.remaining = count;
775     }
776    
777 jsr166 1.76 /** Ensures late-binding initialization; then returns remaining. */
778     private int remaining() {
779     if (remaining < 0) {
780     cursor = head;
781     remaining = size;
782     }
783     return remaining;
784     }
785    
786 jsr166 1.75 public ArrayDequeSpliterator trySplit() {
787 jsr166 1.77 final int mid;
788     if ((mid = remaining() >> 1) > 0) {
789 jsr166 1.75 int oldCursor = cursor;
790 jsr166 1.76 cursor = add(cursor, mid, elements.length);
791 jsr166 1.75 remaining -= mid;
792     return new ArrayDequeSpliterator(oldCursor, mid);
793     }
794     return null;
795     }
796 dl 1.16
797 jsr166 1.75 public void forEachRemaining(Consumer<? super E> action) {
798     Objects.requireNonNull(action);
799     final Object[] elements = ArrayDeque.this.elements;
800     final int capacity = elements.length;
801 jsr166 1.77 int k = remaining();
802     remaining = 0;
803     for (int i = cursor; --k >= 0; i = inc(i, capacity))
804     action.accept(checkedElementAt(elements, i));
805 dl 1.16 }
806    
807 jsr166 1.75 public boolean tryAdvance(Consumer<? super E> action) {
808     Objects.requireNonNull(action);
809 jsr166 1.76 if (remaining() == 0)
810 jsr166 1.75 return false;
811     action.accept(checkedElementAt(elements, cursor));
812     cursor = inc(cursor, elements.length);
813     remaining--;
814     return true;
815     }
816    
817     public long estimateSize() {
818 jsr166 1.76 return remaining();
819 jsr166 1.75 }
820    
821     public int characteristics() {
822     return Spliterator.NONNULL
823     | Spliterator.ORDERED
824     | Spliterator.SIZED
825     | Spliterator.SUBSIZED;
826 dl 1.16 }
827 jsr166 1.75 }
828 dl 1.16
829 jsr166 1.75 @Override
830     public void forEach(Consumer<? super E> action) {
831     // checkInvariants();
832     Objects.requireNonNull(action);
833     final Object[] elements = this.elements;
834     final int capacity = elements.length;
835     for (int k = size, i = head; --k >= 0; i = inc(i, capacity))
836     action.accept(elementAt(i));
837     // checkInvariants();
838     }
839    
840     /**
841     * Replaces each element of this deque with the result of applying the
842     * operator to that element, as specified by {@link List#replaceAll}.
843     *
844     * @param operator the operator to apply to each element
845     */
846 jsr166 1.79 /* TODO: public */ private void replaceAll(UnaryOperator<E> operator) {
847 jsr166 1.75 Objects.requireNonNull(operator);
848     final Object[] elements = this.elements;
849     final int capacity = elements.length;
850     for (int k = size, i = head; --k >= 0; i = inc(i, capacity))
851     elements[i] = operator.apply(elementAt(i));
852     // checkInvariants();
853     }
854    
855     /**
856     * @throws NullPointerException {@inheritDoc}
857     */
858     @Override
859     public boolean removeIf(Predicate<? super E> filter) {
860     Objects.requireNonNull(filter);
861     return bulkRemove(filter);
862     }
863    
864     /**
865     * @throws NullPointerException {@inheritDoc}
866     */
867     @Override
868     public boolean removeAll(Collection<?> c) {
869     Objects.requireNonNull(c);
870     return bulkRemove(e -> c.contains(e));
871     }
872    
873     /**
874     * @throws NullPointerException {@inheritDoc}
875     */
876     @Override
877     public boolean retainAll(Collection<?> c) {
878     Objects.requireNonNull(c);
879     return bulkRemove(e -> !c.contains(e));
880     }
881    
882     /** Implementation of bulk remove methods. */
883     private boolean bulkRemove(Predicate<? super E> filter) {
884     // checkInvariants();
885     final Object[] elements = this.elements;
886     final int capacity = elements.length;
887     int i = head, j = i, remaining = size, deleted = 0;
888     try {
889     for (; remaining > 0; remaining--, i = inc(i, capacity)) {
890     @SuppressWarnings("unchecked") E e = (E) elements[i];
891     if (filter.test(e))
892     deleted++;
893     else {
894     if (j != i)
895     elements[j] = e;
896     j = inc(j, capacity);
897     }
898 jsr166 1.30 }
899 jsr166 1.75 return deleted > 0;
900     } catch (Throwable ex) {
901 jsr166 1.78 if (deleted > 0)
902     for (; remaining > 0;
903     remaining--, i = inc(i, capacity), j = inc(j, capacity))
904     elements[j] = elements[i];
905 jsr166 1.75 throw ex;
906     } finally {
907     size -= deleted;
908     for (; --deleted >= 0; j = inc(j, capacity))
909     elements[j] = null;
910     // checkInvariants();
911 dl 1.16 }
912     }
913    
914 dl 1.1 /**
915 jsr166 1.40 * Returns {@code true} if this deque contains the specified element.
916     * More formally, returns {@code true} if and only if this deque contains
917     * at least one element {@code e} such that {@code o.equals(e)}.
918 dl 1.1 *
919     * @param o object to be checked for containment in this deque
920 jsr166 1.40 * @return {@code true} if this deque contains the specified element
921 dl 1.1 */
922     public boolean contains(Object o) {
923 jsr166 1.58 if (o != null) {
924 jsr166 1.75 final Object[] elements = this.elements;
925     final int capacity = elements.length;
926     for (int k = size, i = head; --k >= 0; i = inc(i, capacity))
927     if (o.equals(elements[i]))
928 jsr166 1.58 return true;
929 dl 1.1 }
930     return false;
931     }
932    
933     /**
934     * Removes a single instance of the specified element from this deque.
935 jsr166 1.9 * If the deque does not contain the element, it is unchanged.
936 jsr166 1.40 * More formally, removes the first element {@code e} such that
937     * {@code o.equals(e)} (if such an element exists).
938     * Returns {@code true} if this deque contained the specified element
939 jsr166 1.12 * (or equivalently, if this deque changed as a result of the call).
940 jsr166 1.9 *
941 jsr166 1.46 * <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}.
942 dl 1.1 *
943 jsr166 1.9 * @param o element to be removed from this deque, if present
944 jsr166 1.40 * @return {@code true} if this deque contained the specified element
945 dl 1.1 */
946 jsr166 1.9 public boolean remove(Object o) {
947     return removeFirstOccurrence(o);
948 dl 1.1 }
949    
950     /**
951     * Removes all of the elements from this deque.
952 jsr166 1.7 * The deque will be empty after this call returns.
953 dl 1.1 */
954     public void clear() {
955 jsr166 1.75 final Object[] elements = this.elements;
956     final int capacity = elements.length;
957     final int h = this.head;
958     final int s = size;
959     if (capacity - h >= s)
960     Arrays.fill(elements, h, h + s, null);
961     else {
962     Arrays.fill(elements, h, capacity, null);
963     Arrays.fill(elements, 0, s - capacity + h, null);
964 dl 1.1 }
965 jsr166 1.75 size = head = 0;
966     // checkInvariants();
967 dl 1.1 }
968    
969     /**
970 dl 1.5 * Returns an array containing all of the elements in this deque
971 jsr166 1.10 * in proper sequence (from first to last element).
972 dl 1.1 *
973 jsr166 1.10 * <p>The returned array will be "safe" in that no references to it are
974     * maintained by this deque. (In other words, this method must allocate
975     * a new array). The caller is thus free to modify the returned array.
976 jsr166 1.13 *
977 jsr166 1.11 * <p>This method acts as bridge between array-based and collection-based
978     * APIs.
979     *
980 dl 1.5 * @return an array containing all of the elements in this deque
981 dl 1.1 */
982     public Object[] toArray() {
983 jsr166 1.50 final int head = this.head;
984 jsr166 1.75 final int firstLeg;
985     Object[] a = Arrays.copyOfRange(elements, head, head + size);
986     if ((firstLeg = elements.length - head) < size)
987     System.arraycopy(elements, 0, a, firstLeg, size - firstLeg);
988 jsr166 1.50 return a;
989 dl 1.1 }
990    
991     /**
992 jsr166 1.10 * Returns an array containing all of the elements in this deque in
993     * proper sequence (from first to last element); the runtime type of the
994     * returned array is that of the specified array. If the deque fits in
995     * the specified array, it is returned therein. Otherwise, a new array
996     * is allocated with the runtime type of the specified array and the
997     * size of this deque.
998     *
999     * <p>If this deque fits in the specified array with room to spare
1000     * (i.e., the array has more elements than this deque), the element in
1001     * the array immediately following the end of the deque is set to
1002 jsr166 1.40 * {@code null}.
1003 jsr166 1.10 *
1004     * <p>Like the {@link #toArray()} method, this method acts as bridge between
1005     * array-based and collection-based APIs. Further, this method allows
1006     * precise control over the runtime type of the output array, and may,
1007     * under certain circumstances, be used to save allocation costs.
1008     *
1009 jsr166 1.40 * <p>Suppose {@code x} is a deque known to contain only strings.
1010 jsr166 1.10 * The following code can be used to dump the deque into a newly
1011 jsr166 1.40 * allocated array of {@code String}:
1012 jsr166 1.10 *
1013 jsr166 1.63 * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
1014 jsr166 1.10 *
1015 jsr166 1.40 * Note that {@code toArray(new Object[0])} is identical in function to
1016     * {@code toArray()}.
1017 dl 1.1 *
1018     * @param a the array into which the elements of the deque are to
1019 jsr166 1.9 * be stored, if it is big enough; otherwise, a new array of the
1020     * same runtime type is allocated for this purpose
1021 jsr166 1.10 * @return an array containing all of the elements in this deque
1022     * @throws ArrayStoreException if the runtime type of the specified array
1023     * is not a supertype of the runtime type of every element in
1024     * this deque
1025     * @throws NullPointerException if the specified array is null
1026 dl 1.1 */
1027 jsr166 1.34 @SuppressWarnings("unchecked")
1028 dl 1.1 public <T> T[] toArray(T[] a) {
1029 jsr166 1.75 final Object[] elements = this.elements;
1030 jsr166 1.50 final int head = this.head;
1031 jsr166 1.75 final int firstLeg;
1032     boolean wrap = (firstLeg = elements.length - head) < size;
1033     if (size > a.length) {
1034 jsr166 1.50 a = (T[]) Arrays.copyOfRange(elements, head, head + size,
1035     a.getClass());
1036     } else {
1037 jsr166 1.75 System.arraycopy(elements, head, a, 0, wrap ? firstLeg : size);
1038     if (size < a.length)
1039 jsr166 1.50 a[size] = null;
1040     }
1041     if (wrap)
1042 jsr166 1.75 System.arraycopy(elements, 0, a, firstLeg, size - firstLeg);
1043 dl 1.1 return a;
1044     }
1045    
1046     // *** Object methods ***
1047    
1048     /**
1049     * Returns a copy of this deque.
1050     *
1051     * @return a copy of this deque
1052     */
1053     public ArrayDeque<E> clone() {
1054 dl 1.5 try {
1055 jsr166 1.34 @SuppressWarnings("unchecked")
1056 dl 1.1 ArrayDeque<E> result = (ArrayDeque<E>) super.clone();
1057 jsr166 1.28 result.elements = Arrays.copyOf(elements, elements.length);
1058 dl 1.1 return result;
1059 dl 1.5 } catch (CloneNotSupportedException e) {
1060 dl 1.1 throw new AssertionError();
1061     }
1062     }
1063    
1064     private static final long serialVersionUID = 2340985798034038923L;
1065    
1066     /**
1067 jsr166 1.38 * Saves this deque to a stream (that is, serializes it).
1068 dl 1.1 *
1069 jsr166 1.56 * @param s the stream
1070 jsr166 1.57 * @throws java.io.IOException if an I/O error occurs
1071 jsr166 1.40 * @serialData The current size ({@code int}) of the deque,
1072 dl 1.1 * followed by all of its elements (each an object reference) in
1073     * first-to-last order.
1074     */
1075 jsr166 1.32 private void writeObject(java.io.ObjectOutputStream s)
1076     throws java.io.IOException {
1077 dl 1.1 s.defaultWriteObject();
1078    
1079     // Write out size
1080 jsr166 1.75 s.writeInt(size);
1081 dl 1.1
1082     // Write out elements in order.
1083 jsr166 1.75 final Object[] elements = this.elements;
1084     final int capacity = elements.length;
1085     for (int k = size, i = head; --k >= 0; i = inc(i, capacity))
1086 dl 1.1 s.writeObject(elements[i]);
1087     }
1088    
1089     /**
1090 jsr166 1.38 * Reconstitutes this deque from a stream (that is, deserializes it).
1091 jsr166 1.56 * @param s the stream
1092 jsr166 1.57 * @throws ClassNotFoundException if the class of a serialized object
1093     * could not be found
1094     * @throws java.io.IOException if an I/O error occurs
1095 dl 1.1 */
1096 jsr166 1.32 private void readObject(java.io.ObjectInputStream s)
1097     throws java.io.IOException, ClassNotFoundException {
1098 dl 1.1 s.defaultReadObject();
1099    
1100     // Read in size and allocate array
1101 jsr166 1.75 elements = new Object[size = s.readInt()];
1102 dl 1.1
1103     // Read in all elements in the proper order.
1104     for (int i = 0; i < size; i++)
1105 jsr166 1.34 elements[i] = s.readObject();
1106 dl 1.1 }
1107 dl 1.41
1108 jsr166 1.75 /** debugging */
1109     private void checkInvariants() {
1110     try {
1111     int capacity = elements.length;
1112     assert size >= 0 && size <= capacity;
1113     assert head >= 0 && ((capacity == 0 && head == 0 && size == 0)
1114     || head < capacity);
1115     assert size == 0
1116     || (elements[head] != null && elements[tail()] != null);
1117     assert size == capacity
1118     || (elements[dec(head, capacity)] == null
1119     && elements[inc(tail(), capacity)] == null);
1120     } catch (Throwable t) {
1121     System.err.printf("head=%d size=%d capacity=%d%n",
1122     head, size, elements.length);
1123     System.err.printf("elements=%s%n",
1124     Arrays.toString(elements));
1125     throw t;
1126 dl 1.41 }
1127     }
1128    
1129 dl 1.1 }