ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.80
Committed: Thu Oct 20 01:43:31 2016 UTC (7 years, 6 months ago) by jsr166
Branch: MAIN
Changes since 1.79: +7 -3 lines
Log Message:
switch future methods to @since TBD

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