ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/ArrayDeque.java
Revision: 1.91
Committed: Tue Oct 25 16:51:17 2016 UTC (7 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.90: +24 -17 lines
Log Message:
use <= 0 instead of == 0 to help VM

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